Reputation: 1906
My configuration class:
@Bean(name = "model")
@Order(1)
public Model model1(){
return new Model(1);
}
@Bean(name = "model")
@Order(2)
public Model model2(){
return new Model(2);
}
As we can see, the two methods create a Bean with the same name, I have used the @Order()
annotation to give priority to one of the beans.
Unfortunately, even if I change the value of the Order to alter between the two annotated Beans, Only the first Bean is used in my code below:
Model bean = (Model) applicationContext.getBean("model");
System.out.println("bean.getId() "+bean.getId());
bean.getId() 1
Do we have two beans on the context? if we have only one, which of the two will be chose and why?
I know that I can use different names to differentiate between the beans, but I'm willing to understand how the @Order
annotation works in parallel with @Bean
.
Upvotes: 1
Views: 1196
Reputation: 58772
After Spring 4 you can get List of Bean ordered by precedence.
@Autowired
private List<Model> models;
And in your method get by index
models.get(0).getModel();
Since Spring 4.0, it supports the ordering of injected components to a collection. As a result, Spring will inject the auto-wired beans of the same type based on their order value.
Upvotes: 3