SpringBoot复习:(45)@Component定义的bean会被@Bean定义的同名的bean覆盖

有同名的bean需要配置:

spring.main.allow-bean-definition-overriding=true

否则报错。

复制代码
package cn.edu.tju.component;

import org.springframework.stereotype.Component;

@Component
public class Person {
    private String name;
    private int age;

    {
        this.name = "nameInComponent";
        this.age =33;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

package cn.edu.tju.config;

import cn.edu.tju.component.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class PersonConfig {
    @Bean("person")
    Person getPerson(){
        Person p = new Person();
        p.setAge(23);
        p.setName("nameInBeanAnnotation");
        return  p;
    }
}

package cn.edu.tju;

import cn.edu.tju.component.Person;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class Start {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Start.class, args);
        Person person = context.getBean("person", Person.class);
        System.out.println(person.getName());

    }
}

运行结果

相关推荐
艾莉丝努力练剑20 分钟前
【C++:异常】C++ 异常处理完全指南:从理论到实践,深入理解栈展开与最佳实践
java·开发语言·c++·安全·c++11
武子康21 分钟前
Java-184 缓存实战:本地缓存 vs 分布式缓存(含 Guava/Redis 7.2)
java·redis·分布式·缓存·微服务·guava·本地缓存
小马爱打代码6 小时前
Spring Boot:模块化实战 - 保持清晰架构
java·spring boot·架构
小坏讲微服务7 小时前
SpringBoot4.0整合knife4j 在线文档完整使用
java·spring cloud·在线文档·knife4j·文档·接口文档·swagger-ui
8***Z897 小时前
springboot 异步操作
java·spring boot·mybatis
i***13247 小时前
Spring BOOT 启动参数
java·spring boot·后端
坚持不懈的大白7 小时前
后端:SpringMVC
java
IT_Octopus7 小时前
(旧)Spring Securit 实现JWT token认证(多平台登录&部分鉴权)
java·后端·spring
kk哥88997 小时前
Spring详解
java·后端·spring
S***26757 小时前
Spring Cloud Gateway 整合Spring Security
java·后端·spring