有同名的bean需要配置:
spring.main.allow-bean-definition-overriding=true
否则报错。文章来源:https://www.toymoban.com/news/detail-649455.html
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());
}
}
运行结果
文章来源地址https://www.toymoban.com/news/detail-649455.html
到了这里,关于SpringBoot复习:(45)@Component定义的bean会被@Bean定义的同名的bean覆盖的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!