java - 如何使用 Spring 4 Autowiring 泛型类?

标签 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());
    }
}

还有另一个使用 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/

相关文章:

java - 在 merge 方法中返回多个变量

java - 如何修复 "HTTP Status 404"Spring MVC

java - 您是否应该在 server.xml 或 context.xml 中设置数据库连接属性

java - Axis 1 客户端与 Axis 2 Web 服务不兼容

java - 是否可以将 Ear 模块定义为多模块项目中的父模块?

c# - 通用 View 和 Controller 以避免 MVC 中的重复代码

class - Typescript 访问泛型类型的静态属性

java - 确保输入参数满足多个类型标准

Java PDFBox - 阅读和修改带有特殊字符(变音符号)的 pdf

java - 通过@Configuration、@Bean和@Component进行Spring依赖注入(inject)