Spring 4generics类,获取参数化类型
您在Spring中有一个Generic类,我想为注入的bean获取通用的T类类。 我知道Java中的经典方法,并了解Spring 4如何实现Java Generics 。 此外,我试图找到一个使用ResolvableType的解决方案但没有任何作用。
@Autowired GenericDao specificdao;
public GenericDaoImpl { private Class type; public DaoImpl () { this.type = ...? } public T findById(Serializable id) { return (T) HibernateUtil.findById(type, id); } }
有什么方法可以避免这种情况吗?
@Autowired @Qualifier GenericDao specificdao;
@Repository("specificdao") public SpecificDaoImpl extends GenericDao { public SpecificDaoImpl () { // assuming the constructor is implemented in GenericDao super(this.getClass()) } }
谢谢。
好的,如果我理解你的问题:你想要实现的目标非常棘手。
您可以使用TypeTools ,然后执行以下操作:
import net.jodah.typetools.TypeResolver; public GenericDaoImpl { private Class type; public GenericDaoImpl () { Class>[] typeArguments = TypeResolver.resolveRawArguments(GenericDaoImpl.class, getClass()); this.type = (Class ) typeArguments[0]; } public T findById(Serializable id) { return (T) HibernateUtil.findById(type, id); } }
但我仍然怀疑这是不是一个好主意 。 因为通常你不想要:
@Autowired GenericDao specificDao;
但反而:
@Autowired SpecificDao specificDao;
为什么? 因为每个DAO几乎总是与其他DAO完全不同的方法。 所有通用的唯一通用方法可能是: findById
, findAll
, save
, count
, delete
等。
因此,从GenericDAOinheritance子类是最明显的方法,因为它允许您在具体的DAO中添加任何所需的方法。
顺便说一句:您说过要自己重新实现Spring Datafunction。 但请注意,在Spring方式中,您仍然需要创建具体的存储库。