Spring 3.2 Autowire通用类型


问题内容

因此,在Spring 3.2中我有许多泛型,理想情况下,我的体系结构应如下所示。

class GenericDao<T>{}

class GenericService<T, T_DAO extends GenericDao<T>>
{
    // FAILS
    @Autowired
    T_DAO;
}

@Component
class Foo{}

@Repository
class FooDao extends GenericDao<Foo>{}

@Service
FooService extends GenericService<Foo, FooDao>{}

不幸的是,对于泛型的多种实现,自动装配会引发关于多个匹配bean定义的错误。我认为这是因为@Autowired类型擦除之前的过程。我找到或想出的每个解决方案在我看来都是难看的,或者莫名其妙地拒绝了。解决此问题的最佳方法是什么?


问题答案:

如何向中添加构造函数GenericService并将自动装配移至扩展类,例如

class GenericService<T, T_DAO extends GenericDao<T>> {
    private final T_DAO tDao;

    GenericService(T_DAO tDao) {
        this.tDao = tDao;
    }
}

@Service
FooService extends GenericService<Foo, FooDao> {

    @Autowired
    FooService(FooDao fooDao) {
        super(fooDao);
    }
}

更新:

Spring 4.0 RC1开始,可以基于泛型类型进行自动装配,这意味着您 可以 编写诸如

class GenericService<T, T_DAO extends GenericDao<T>> {

    @Autowired
    private T_DAO tDao;
}

并创建多个不同的Spring bean,例如:

@Service
class FooService extends GenericService<Foo, FooDao> {
}