java - @Order 与 @Bean 注释的方法行为

标签 java spring autowired spring-bean

我的配置类:

@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/

相关文章:

java - Spring 中的单例与 Autowired 字段

java - 在字段中显示文本

Java Spring CRUD 存储库方法 "deleteById"不起作用

java - Neo4j Spring SocketTimeoutError 错误

spring - 如何在Spring webflux WebExceptionHandlder中将消息写入http body

spring - mock Spring Bean

java - spring boot中如何访问非主DataSource?

java:如何停止等待很长时间的线程

java - 如何在Java中滚动文本输出?

spring - Spock 如何在方法中模拟 Autowired 类的函数调用