簡體   English   中英

Spring 4泛型類,獲取參數化類型

[英]Spring 4 generic class, get the parametrized type

您在Spring中有一個Generic類,我想為注入的bean獲取通用的T類類。 我知道Java中經典方法,了解Spring 4如何實現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完全不同的方法。 所有通用的唯一通用方法可能是: findByIdfindAllsavecountdelete等。

因此,從GenericDAO繼承子類是最明顯的方法,因為它允許您在具體的DAO中添加任何所需的方法。

順便說一句:你說你想要自己重新實現Spring Data功能。 但請注意,在Spring方式中,您仍然需要創建具體的存儲庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM