所以我在 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>{}
不幸的是,对于泛型的多个实现, Autowiring 会引发关于多个匹配 bean 定义的错误。我认为这是因为 @Autowired
在类型删除之前处理。我发现或提出的每个解决方案对我来说都很难看,或者只是莫名其妙地拒绝工作。解决此问题的最佳方法是什么?
最佳答案
如何将构造函数添加到 GenericService
并将 Autowiring 移动到扩展类,例如
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 ,可以基于泛型类型 Autowiring ,这意味着您可以编写类似的泛型服务
class GenericService<T, T_DAO extends GenericDao<T>> {
@Autowired
private T_DAO tDao;
}
并创建多个不同的 Spring bean,例如:
@Service
class FooService extends GenericService<Foo, FooDao> {
}
关于java - Spring 3.2 Autowire 泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14368339/