gpt4 book ai didi

java - Spring 4泛型类,获取参数化类型

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:17:01 25 4
gpt4 key购买 nike

您好,在 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 完全不同的方法。唯一通用的通用方法可能是:findByIdfindAllsavecount删除

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

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

关于java - Spring 4泛型类,获取参数化类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33940633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com