我的课程如下:
class Foo<KeyType, ValueType> {
private Producer<KeyType, ValueType> kafkaProducer;
public Foo() {
this.kafkaProducer = new Producer<KeyType, ValueType>(new ProducerConfig());
}
}
还有另一个使用此Foo类的DAO类,如下所示:
class CompanyDao {
@Autowired
private Foo<String, Integer> fooHelper;
}
我希望Spring在Foo
对象中注入fooHelpder
类型的对象。为此,我使用以下XML配置:
<bean id="fooHelper" class="com.ask.util.Foo">
<property name="KeyType" value="java.lang.String" />
<property name="ValueType" value="Integer" />
</bean>
<bean id="CompanyDao" class="com.ask.dao.CompanyDao">
<property name="fooHelper"><ref bean="fooHelder"/></property>
</bean>
当我使用这个XML配置时,Spring会抛出以下错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fooHelper' defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'KeyType' of bean class [com.ask.util.fooHelper]: Bean property 'KeyType' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1361)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
知道如何解决此错误吗?
答案 0 :(得分:2)
需要进行两项更改。
第一个因为Spring 4现在在注入期间使用Generics(Pre Spring 4版本忽略了泛型):
class CompanyDao {
private Foo<KeyType, ValueType> fooHelper;
}
(使用XML配置时不需要注释)
和
<bean id="fooHelper" class="com.ask.util.Foo">
</bean>
<bean id="CompanyDao" class="com.ask.dao.CompanyDao">
<property name="fooHelper"><ref bean="fooHelder"/></property>
</bean>
答案 1 :(得分:0)
使用setter方法将KeyType和ValueType属性添加到您的类中。