@Configuration
public class Config {
@Bean
public Student getStudent() {
return new Student();
}
}
@Component
public class Config {
@Bean
public Student getStudent() {
return new Student();
}
}
我想知道使用上述两种方法初始化bean与工厂的区别。
答案 0 :(得分:1)
两个@Component
和@Configuration
bean方法注册之间存在根本不同。
如果在@Bean
内声明@Configuration
方法,它将被包装到CGLIB包装器中。进一步调用@Bean
方法返回相同的bean实例。
那是:
@Configuration
class A {
@Bean
BeanX getBeanX() { ... };
@Bean
BeanY getBeanY() {
return new BeanY(getBeanX()); // You got the same bean instance from getBeanX() method, no matter how many times you call it
// This instance is the container singleton instance
}
}
如果使用@Component
,则每次调用bean方法时,都会创建另一个bean:
@Component
class B {
@Bean
BeanX getBeanX() { ... };
@Bean
BeanY getBeanY() {
return new BeanY(getBeanX()); // You got the different bean instance every time you call it
// This getBeanX() instance is different from container singleton instance
}
}