Description
Modestas Kažinauskas opened SPR-13980 and commented
@Primary
annotation is not working for beans. This issue persists in older spring versions too.
Please see my code below
@Configuration
public class ConfigA {
@Bean
@Primary
public MyObject createMyObject() {
return new MyObject("A");
}
}
@Configuration
public class ConfigB {
@Bean
public MyObject createMyObject() {
return new MyObject("B");
}
}
public class MyObject {
private String name;
public MyObject(String name) {
this.name = name;
}
...
}
@Configuration
public class Runner {
@Autowired
private MyObject myObject;
@PostConstruct
void init() {
System.out.println(myObject.getName()); //Output is B, but primary bean is A
}
}
2016-02-25 08:39:49.351 INFO 1196 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'init' with a different definition: replacing
[Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=true; factoryBeanName=configA; factoryMethodName=createMyObject; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/modzo/ConfigA.class]]
with
[Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=configB; factoryMethodName=createMyObject; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/modzo/ConfigB.class]]
DefaultListableBeanFactory takes bean name as 'init'. and overrides with another.
This configuration is resolved by changing init method name to not duplicate.
Affects: 4.2.4
Reference URL: #15434
Issue Links:
- Reconsider whether to generally allow bean overriding by name [SPR-10808] #15434 Reconsider whether to generally allow bean overriding by name