春天多个autowire候选人

时间:2017-06-08 10:32:56

标签: java spring autowired

我想解决以下问题。在Spring项目上工作,我有一个spring bean配置类。

package package.bean_config_java;


@Configuration
@ComponentScan("package.bean_config_java")
public class Beans {

  @Bean
  public Customer customerHashmark() {
    Customer c = new Customer();
    c.setFormatter(hashmarkNameFormatter());

    return c;
  }

  @Bean
  public Customer customerUnderscore() {
    Customer c = new Customer();
    c.setFormatter(underscoreNameFormatter());

    return c;
  }

  @Bean
  public Formatter hashmarkNameFormatter() {
    return new HashmarkNameFormatter();
  }

  @Primary
  @Bean
  public Formatter underscoreNameFormatter() {
    return new UnderscoreNameFormatter();
  }
}

在我从容器中询问任何客户后,它会返回一个带有underscoreNameFormatter的客户。

我尝试调试这个,发现spring在app启动期间只调用一次customer.setFormatter,而origin是我的配置类,所以看起来没问题,但最后,当我从ctx取回我的bean时。 getBean方法,在所有情况下,formater都是underscoreNameFormatter。

甚至可以覆盖注入的值?

注意:使用xml配置可以执行此操作

<bean class="package.Customer">
  <property name="formatter">
    <bean class="package.HashmarkNameFormatter" />
  </property>
</bean>

2 个答案:

答案 0 :(得分:0)

因为在@Configuration类中调用了setter c.setFormatter(hashmarkNameFormatter());,所以此调用将从应用程序上下文中设置Formatter bean,在您的情况下,该上下文不是hashmarkNameFormatter方法返回的对象,而是UnderscoreNameFormatter。

我认为如果您想为customerUnderscore设置UnderscoreNameFormatter,您可以通过指定类型化的Formatter将其作为参数注入customerHashmark bean创建方法:

E.g。

@Bean
public Customer customerHashmark(HashmarkNameFormatter hashmarkNameFormatter) {
    Customer c = new Customer();
    c.setFormatter(hashmarkNameFormatter);

    return c;
}

答案 1 :(得分:0)

命名所有bean并使用@Qualifier注入它们。

package package.bean_config_java;

@Configuration
@ComponentScan("package.bean_config_java")
public class Beans {

  @Bean(name="hashmarkNameCustomer")
  public Customer customerHashmark() {
    Customer c = new Customer();
    c.setFormatter(hashmarkNameFormatter());

    return c;
  }

  @Bean(name="underscoreNameCustomer")
  public Customer customerUnderscore() {
    Customer c = new Customer();
    c.setFormatter(underscoreNameFormatter());

    return c;
  }

  @Bean
  public Formatter hashmarkNameFormatter() {
    return new HashmarkNameFormatter();
  }

  @Primary
  @Bean
  public Formatter underscoreNameFormatter() {
    return new UnderscoreNameFormatter();
  }
}

当您需要拥有HashmarkNameFormatter的客户时,您只需:

@Autowired
@Qualifier("hashmarkNameCustomer")
Customer customer1;

对于使用UnderscoreNameFormatter的客户:

@Autowired
@Qualifier("underscoreNameCustomer")
Customer customer2;