Java 如何使用Spring4自动连接泛型类?

Java 如何使用Spring4自动连接泛型类?,java,spring,generics,inversion-of-control,spring-4,Java,Spring,Generics,Inversion Of Control,Spring 4,我的课程如下: class Foo<KeyType, ValueType> { private Producer<KeyType, ValueType> kafkaProducer; public Foo() { this.kafkaProducer = new Producer<KeyType, ValueType>(new ProducerConfig()); } } class CompanyDao {

我的课程如下:

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

    public Foo() {
        this.kafkaProducer = new Producer<KeyType, ValueType>(new ProducerConfig());
    }
}
class CompanyDao {
    @Autowired
    private Foo<String, Integer> fooHelper;
}
使用此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)

知道如何解决此错误吗?

需要进行两项更改

第一个原因是Spring4现在在注入期间使用泛型(Spring4之前的版本忽略了泛型):

class CompanyDao{
私人富富佣工;
}
(使用XML配置时不需要注释)



使用setter方法向类添加KeyType和ValueType属性。

可以显示getter和setter方法吗?只需删除两个属性
KeyType
ValueType
@Tunaki,thaks。删除这两个属性后,它就工作了。顺便说一下:KeyType、ValueType是类的类型参数。属性(在Spring中使用)是类似CompanyDao中的fooHelper的字段(或setter)。所以键入参数!=财产。这就是它不起作用的原因。哪门课?CompanyDao类还是Foo类?实际上,您的Foo类将被修改为
Foo
,并将KeyType和ValueType作为属性。
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)
class CompanyDao {
    private Foo<KeyType, ValueType> fooHelper;
}
<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>