使用不同的constructor-args创建同一个类的2个bean并使用自动装配

时间:2015-11-28 08:59:37

标签: java spring spring-mvc spring-security

您好我正在开发一个项目,我需要在其中创建2个相同类但不同构造函数的bean实例。现在只有“生产环境”的功能,所以我有xml文件,如:

<context:component-scan base-package="com.xxx.yyy" /> 
    <bean id="id1" class="someCompanySpecificURLForTheClass" scope="singleton"/>

  <bean name="name1" factory-bean="id1" factory-method="createFullClient">
    <constructor-arg index="0">
        <ref bean="someJSONBean"/>
    </constructor-arg>
    <constructor-arg value="productionEnv" index="1"/>
</bean>  

</beans>

现在我还需要包含测试环境的功能。所以我将xml文件更改为:

<context:component-scan base-package="com.xxx.yyy" />
<context:component-scan base-package="com.zzz.yyy" /> 

 <bean id="id1" class="someCompanySpecificURLForTheClass" scope="prototype"/>

  <bean name="name1" factory-bean="id1" factory-method="createFullClient">
    <constructor-arg index="0">
        <ref bean="someJSONBean"/>
    </constructor-arg>
    <constructor-arg value="${value.name}" index="1"/>
</bean> 

在2个Java文件中,我对 setClients()的方法和 someJSONBean 的对象使用 @Autowired 注释。

但我收到错误:

BeanCreationException: could not autowire method: public void com.zzz.yyy.sometthing.setClients(someCompanySpecificURLForTheClass) throws IllegalArgumentException and UnsupportedEncodingException.
nested exception is defined: NoSuchBeanDefinitionException: no unique bean of type(someCompanySpecificURLForTheClass) is defined: expected single matching bean, found 2(name1, name2).

我是Spring框架的新手。任何人都可以告诉我们发生了什么错误,是自动装配我做错了吗?我怎么能解决这个问题?

编辑: 这里 someCompanySpecificURLForTheClass 是同一个类,bean(name1和name2)使用这个bean作为具有不同构造函数参数的工厂bean。
我使用的是弹簧3.1 经过大量搜索,我想我可以使用占位符来构造 - args值吗? 以上是正在使用的已编辑的xml文件。 更新了Java类中的代码: 1.

@ConfigAdapter
 class class1{

  @Autowired
  private someJSONBean obj;

  @Autowired
  @Value("${value.name:thisismyvalue}")
  public void setClients(){}
}

 @ConfigAdapter
 class class2{

  @Autowired
  private someJSONBean obj;

  @Autowired
  @Value("${value.name:thisismyvalue}")
  public void setClients(){}
}

但是我收到以下错误:

ConversionNotSupportedException: failed to convert 'java.lang.string' to 'someCompanySpecificURLForTheClass'.
nested execption is IllegalStateException
Cannot convert 'java.lang.string' to 'someCompanySpecificURLForTheClass' of required type: no matching editors or conversion strategy found.

我是否错误地指定了注释值? 为什么会这样?

1 个答案:

答案 0 :(得分:1)

您必须使用@Qualifier注释和@Autowired。由于您正在创建两个相同类的bean,因此spring不知道哪个bean为autowire。您可以使用@Qualifer("id/name")注释提供提示。

@Autowired
@Qualifier("name1")
 //yourProperty

@Autowired
@Qualifier("name2")
//yourProperty

查看此link

如果你想将bean注入你的类,那么你有两个创建两个不同的属性,每个属性指向不同的实例。

@Autowired
@Qualifer("name1")
//property1

@Autowired
@Qualifer("name2")
//property2