Spring 3.2 Autowire泛型类型 [英] Spring 3.2 Autowire generic types

查看:420
本文介绍了Spring 3.2 Autowire泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class GenericDao< p>< p> T> {} 

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

@Component
class Foo {}

@Repository
class FooDao extends GenericDao< Foo> {}

@Service
FooService扩展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扩展GenericService< Foo,FooDao> {

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


$ / code $ / pre

$ hr

更新:



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> {
}


So I have a number of generics in Spring 3.2 and ideally my architecture would look something like this.

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>{}

Unfortunately with multiple implementations of the generics the autowiring throws an error about multiple matching bean definitions. I assume this is because @Autowired processes before type erasure. Every solution I've found or come up with looks ugly to me or just inexplicably refuses to work. What is the best way around this problem?

解决方案

How about adding a constructor to the GenericService and move the autowiring to the extending class, e.g.

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);
    }
}


Update:

As of Spring 4.0 RC1, it is possible to autowire based on generic type, which means that you can write a generic service like

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

    @Autowired
    private T_DAO tDao;
}

and create multiple different Spring beans of it like:

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

这篇关于Spring 3.2 Autowire泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆