如何使用Spring 4自动装配泛型类?

3

我有以下的类:

class Foo<KeyType, ValueType> {
    private Producer<KeyType, ValueType> kafkaProducer;

    public Foo() {
        this.kafkaProducer = new Producer<KeyType, ValueType>(new ProducerConfig());
    }
}

有另一个DAO类使用了这个Foo类,它看起来如下所示:
class CompanyDao {
    @Autowired
    private Foo<String, Integer> fooHelper;
}

我希望Spring可以在fooHelper对象中注入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)

有什么办法可以解决这个错误吗?

你能展示一下你的getter和setter方法吗? - SWiggels
2
只需删除 KeyTypeValueType 两个属性:<bean id="fooHelper" class="com.ask.util.Foo" /> - Tunaki
@Tunaki,谢谢。移除这两个属性后,它就可以工作了。 - Shekhar
1
顺便提一下:KeyType,ValueType是您类的类型参数。属性(如Spring中使用的)是字段(或setter),例如CompanyDao中的fooHelper。因此,类型参数!=属性。这就是为什么它没有起作用的原因。 - Sergej Werfel
2个回答

2

需要进行两个更改。

第一个更改是因为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>

0
请在您的类中添加KeyType和ValueType属性,并使用setter方法。

哪个类?CompanyDao类还是Foo类? - Shekhar
实际上,你的Foo类将被修改为Foo<String, Integer>,并且会有KeyType和ValueType作为属性。 - Rahul Yadav

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接