作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
您好,在 Spring 中有一个泛型类,我想为注入(inject)的 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())
}
}
谢谢。
最佳答案
如果我理解你的问题:你想要实现的目标非常棘手。
您可以使用 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 完全不同的方法。唯一通用的通用方法可能是:findById
、findAll
、save
、count
、删除
等
因此从 GenericDAO 继承子类是最明显的方法,因为它允许您在具体的 DAO 中添加任何需要的方法。
顺便说一句:你说你想自己重新实现 Spring Data 功能。但请注意,在 Spring 方式中,您仍然必须创建具体的存储库。
关于java - Spring 4泛型类,获取参数化类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33940633/
我是一名优秀的程序员,十分优秀!