我有如下类:
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 在 fooHelpder
对象中注入(inject)类型为 Foo
的对象。为此,我使用以下 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)
知道如何解决这个错误吗?
最佳答案
需要进行两项更改。
第一个是因为 Spring 4 现在在注入(inject)期间使用泛型(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>
关于java - 如何使用 Spring 4 Autowiring 泛型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32454255/