简体   繁体   中英

@Order with @Bean annotated method behaviour

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM