[英]Creating 2 beans of the same class with different constructor-args and using autowiring
嗨,我正在做一個項目,在這個項目中,我需要創建2個相同類但不同的構造函數arg的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。
我正在使用Spring 3.1。
經過大量搜索之后,我認為我可以使用占位符作為Constructor-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.
我是否錯誤地指定了注釋值? 為什么會這樣呢?
您必須將@Qualifier
注釋與@Autowired
一起使用。 由於您正在創建兩個相同類的bean,因此spring不知道該autowire
哪個autowire
。 您可以使用@Qualifer("id/name")
注釋給出提示。
@Autowired
@Qualifier("name1")
//yourProperty
要么
@Autowired
@Qualifier("name2")
//yourProperty
查看此鏈接 。
如果要將兩個bean都注入到類中,則您有兩個創建兩個不同的屬性,每個屬性指向一個不同的實例。
@Autowired
@Qualifer("name1")
//property1
@Autowired
@Qualifer("name2")
//property2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.