我的配置类:
@Bean(name = "model")
@Order(1)
public Model model1(){
return new Model(1);
}
@Bean(name = "model")
@Order(2)
public Model model2(){
return new Model(2);
}
正如我们所看到的,这两个方法创建了一个同名的 Bean,我使用了 @Order()
注解优先考虑其中一个 Bean。
不幸的是,即使我更改 Order 的值以在两个带注释的 Bean 之间进行更改,在下面的代码中仅使用第一个 Bean:
Model bean = (Model) applicationContext.getBean("model");
System.out.println("bean.getId() "+bean.getId());
bean.getId() 1
上下文中有两个 bean 吗?如果我们只有一个,会选择两者中的哪一个,为什么?
我知道我可以使用不同的名称来区分 bean,但我愿意了解 @Order
注释如何与 @Bean
并行工作。
最佳答案
Spring 4之后您可以获得List of Bean按优先级排序。
@Autowired
private List<Model> models;
并在您的方法中通过索引获取
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.
关于java - @Order 与 @Bean 注释的方法行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57080876/