【问题标题】:Spring Java Config - @Bean Overriding Bean definition not workingSpring Java Config - @Bean 覆盖 Bean 定义不起作用
【发布时间】:2015-10-07 15:44:05
【问题描述】:

我在项目 A 中有一个名为 Customer 的 bean。在项目 B 中,我将项目 A 作为 maven 依赖项。

在项目 B 的 Java Config (@Configuration) 中,我尝试获取名为 CustomerImpl 的 bean Customer 的新实现。

@Bean
public Customer customer() {
return new CustomerImpl()
}

这里的客户是一个类。

但我的上下文总是有我想要的 Customer 而不是 CustomerImpl。

当我在上面的配置中放置 @Qualifier 并使用该限定符名称而不是 customer() 时,它工作正常。但我不想指定限定符。

【问题讨论】:

  • Customer 是类还是接口?
  • 客户是这里的一个类。

标签: java spring spring-mvc spring-java-config spring-bean


【解决方案1】:

在您的评论中,您说 Customer 是一个类。

尝试将 customer() 方法的返回类型定义为接口(例如 ICustomer),而不是类。让 Customer 和 CustomerImpl 都实现该接口。

@Bean
public ICustomer customer() {
return new CustomerImpl()
}

【讨论】:

  • 你的意思是 CustomerImpl 作为接口??
  • @user2069929 不,创建一个新接口(例如 ICustomer)并让 Customer 和 CustomerImpl 类实现该接口。然后更改 customer 方法以返回 ICustomer 而不是 Customer。
【解决方案2】:

给这两个 bean 起不同的名字,例如

@Bean(name=customerImpl)
public Customer customerImpl() {
  return new CustomerImpl()
}

并使用名称来获取您想要的实例,例如

@Resource(name=customerImpl)
private Customer customer;

【讨论】:

    【解决方案3】:

    问题已解决。进行了 2 处更改。添加了@Primary 并给出了不同的方法名称

    @Primary
    @Bean
    public Customer newMethodName() {
    return new CustomerImpl()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 2017-02-18
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      相关资源
      最近更新 更多