簡體   English   中英

如何使用Spring 4自動化通用類?

[英]How to Autowire generic class using Spring 4?

我的課程如下:

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對象中注入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現在在注入期間使用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>

使用setter方法將KeyType和ValueType屬性添加到您的類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM