【问题标题】:Spring 4 generic class, get the parametrized typeSpring 4泛型类,获取参数化类型
【发布时间】:2015-11-26 14:02:34
【问题描述】:

嗨,Spring 中有一个通用类,我想为注入的 bean 获取通用 T 类型类。我知道classic way in Java 并阅读how Spring 4 implements Java Generics。另外,我尝试使用ResolvableType 找到解决方案,但没有任何效果。

@Autowired
GenericDao<SpecificClass> specificdao;

public GenericDaoImpl <T> {

    private Class<T> type;

    public DaoImpl () { 
         this.type = ...? 
    }

    public T findById(Serializable id) {
        return (T) HibernateUtil.findById(type, id);
    }
}

有没有办法避免这种情况?

@Autowired
@Qualifier
GenericDao<SpecificClass> specificdao;

@Repository("specificdao")
public SpecificDaoImpl extends GenericDao<SpecificClass> {
      public SpecificDaoImpl () {
          // assuming the constructor is implemented in GenericDao
          super(this.getClass())
      }
}

谢谢。

【问题讨论】:

  • 我可能是错的,但我怀疑这是否可以轻松完成(由于类型擦除)。顺便说一句:从您提供的代码来看,您似乎正在尝试重新实现 Spring Data 提供的功能。为什么不使用它呢?
  • 是的,但我会自己做。谢谢。
  • 一个小注释:如果从超类GenericDaoImpl 调用,结果this.getClass() 将是相同的,因为getClass() 返回运行时类型。所以类对象不需要是GenericDaoImpl构造函数的参数,GenericDaoImpl可以自己调用。
  • 另外:你不需要 findById 中的未经检查的强制转换,因为你有类对象。你可以使用return this.type.cast(HibernateUtil.findById(type, id));,它更安全一点,因为它实际上会检查结果是否是正确的类型。
  • This answer 似乎包含几乎相同的信息。

标签: java spring generics


【解决方案1】:

如果我理解您的问题:您想要实现的目标非常棘手。

您可以使用TypeTools,然后执行以下操作:

import net.jodah.typetools.TypeResolver;

public GenericDaoImpl <T> {

    private Class<T> type;

    public GenericDaoImpl () { 
         Class<?>[] typeArguments = TypeResolver.resolveRawArguments(GenericDaoImpl.class, getClass());
         this.type = (Class<T>) typeArguments[0];
    }

    public T findById(Serializable id) {
        return (T) HibernateUtil.findById(type, id);
    }
}

但我仍然怀疑这是否是个好主意。因为通常你不想要:

@Autowired
GenericDao<SpecificClass> specificDao;

但是:

@Autowired
SpecificDao specificDao;

为什么?因为每个 DAO 几乎总是具有与其他 DAO 完全不同的方法。唯一通用的通用方法可能是:findByIdfindAllsavecountdelete 等。

因此,从 GenericDAO 继承子类是最明显的方式,因为它允许您在具体 DAO 中添加任何需要的方法。

顺便说一句:您说过您希望自己重新实现 Spring Data 功能。但请注意,在 Spring 方式中,您仍然需要创建具体的存储库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 2011-09-03
    相关资源
    最近更新 更多