Spring 注释是否应该在@configuration 中定义的类 @Bean 上工作?
Are Spring Annotations supposed to work on @Bean defined classes in @configuration?
所以阅读 @Lookup
文档它说它不会在 @configuration
类 中的工厂方法上工作,我读过 spring 注释不会每当我们使用新的实例化时都会处理。
所以我尝试了,@autowired
注释在 @Bean
定义的实例上工作:
@Configuration
@ComponentScan("autowired_qualifier_resource")
public class Application {
@Bean(name="firstBean")
@Qualifier("qualifierBean")
TestBeanInterface myBean(){
return new TestBean1();
}
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(Application.class);
System.out.println(context.getBean("firstBean"));
}
}
public class TestBean1 implements TestBeanInterface {
private BeanInterface bean;
@Autowired
public TestBean1(){
System.out.println("TestBean1");
}
@Autowired
public void setBean( BeanInterface bean){
System.out.println("SetBean :" + bean);
this.bean = bean;
}
}
setBean
方法被调用并给出了同一类型有多个对象的错误。
那么,为什么查找方法在 @Bean
定义的 类 上不起作用,而其他注释却起作用?
来自docs
Such lookup methods can have default (stub) implementations that will
simply get replaced by the container, or they can be declared as
abstract - for the container to fill them in at runtime. In both
cases, the container will generate runtime subclasses of the method's
containing class via CGLIB, which is why such lookup methods can only
work on beans that the container instantiates through regular
constructors: i.e. lookup methods cannot get replaced on beans
returned from factory methods where we cannot dynamically provide a
subclass for them.
我希望这是不言自明的。
所以阅读 @Lookup
文档它说它不会在 @configuration
类 中的工厂方法上工作,我读过 spring 注释不会每当我们使用新的实例化时都会处理。
所以我尝试了,@autowired
注释在 @Bean
定义的实例上工作:
@Configuration
@ComponentScan("autowired_qualifier_resource")
public class Application {
@Bean(name="firstBean")
@Qualifier("qualifierBean")
TestBeanInterface myBean(){
return new TestBean1();
}
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(Application.class);
System.out.println(context.getBean("firstBean"));
}
}
public class TestBean1 implements TestBeanInterface {
private BeanInterface bean;
@Autowired
public TestBean1(){
System.out.println("TestBean1");
}
@Autowired
public void setBean( BeanInterface bean){
System.out.println("SetBean :" + bean);
this.bean = bean;
}
}
setBean
方法被调用并给出了同一类型有多个对象的错误。
那么,为什么查找方法在 @Bean
定义的 类 上不起作用,而其他注释却起作用?
来自docs
Such lookup methods can have default (stub) implementations that will simply get replaced by the container, or they can be declared as abstract - for the container to fill them in at runtime. In both cases, the container will generate runtime subclasses of the method's containing class via CGLIB, which is why such lookup methods can only work on beans that the container instantiates through regular constructors: i.e. lookup methods cannot get replaced on beans returned from factory methods where we cannot dynamically provide a subclass for them.
我希望这是不言自明的。