[英]@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.如我们所见,这两个方法创建了一个同名的Bean,我使用了
@Order()
注释来优先考虑其中一个Bean。
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:不幸的是,即使我更改 Order 的值以在两个带注释的 Bean 之间进行更改,下面的代码中也仅使用了第一个 Bean :
Model bean = (Model) applicationContext.getBean("model");
System.out.println("bean.getId() "+bean.getId());
bean.getId() 1
bean.getId() 1
Do we have two beans on the context?我们在上下文中有两个 bean 吗? 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
.我知道我可以使用不同的名称来区分 bean,但我愿意了解
@Order
注释如何与@Bean
并行@Bean
。
After Spring 4 you can get List of Bean ordered by precedence.在 Spring 4 之后,您可以获得按优先级排序的 Bean 列表。
@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.
从 Spring 4.0 开始,它支持将注入的组件排序到集合中。 As a result, Spring will inject the auto-wired beans of the same type based on their order value.
因此,Spring 将根据它们的 order 值注入相同类型的自动连接的 bean。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.