So reading on the @Lookup
documentation it says it wont work on factory methods in the @configuration
classes, and I've read that spring annotations wont be processed whenever we use the new instantiation.
So I tried, and the @autowired
annotations work on @Bean
defined instances:
@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;
}
}
The setBean
method is called and gives the error of having more than one object for same type.
So why doesn't the lookup method work on @Bean
defined classes when other annotations do?
From 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.
I hope that is self explanatory.