【发布时间】:2016-03-02 08:55:04
【问题描述】:
您好,我在一个项目中工作,在该项目中,我需要创建 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。
经过大量搜索,我想我可以使用占位符作为构造函数参数值,对吧?
以上是正在使用的编辑过的 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.
我是否错误地指定了注释值? 为什么会这样?
【问题讨论】:
-
你收到什么样的错误?
标签: java spring spring-mvc spring-security