[英]Spring IoC and Generic Interface Type Implementation
最初基於此線程:
還有這個
使用注釋使用Spring Hibernate編寫更少的DAO
我想知道如何實現前者的想法。 可以說我有
@Repository
@Transactional
public class GenericDaoImpl<T> implements GenericDao<T> {
@Autowired
private SessionFactory factory;
private Class<T> type;
public void persist(T entity){
factory.getCurrentSession().persist(entity);
}
@SuppressWarnings("unchecked")
public T merge(T entity){
return (T) factory.getCurrentSession().merge(entity);
}
public void saveOrUpdate(T entity){
factory.getCurrentSession().merge(entity);
}
public void delete(T entity){
factory.getCurrentSession().delete(entity);
}
@SuppressWarnings("unchecked")
public T findById(long id){
return (T) factory.getCurrentSession().get(type, id);
}
}
我可以使用標記器接口:
public interface CarDao extends GenericDao<Car> {}
public interface LeaseDao extends GenericDao<Lease> {}
但是我想通過1 GenericDaoImpl(類似於上面的GenericDaoImpl)來實現細節,以避免為簡單的CRUD編寫重復的Impl。 (我將為需要更高級DAO功能的實體編寫自定義Impl。)
因此,最終可以在我的控制器中執行以下操作:
CarDao carDao = appContext.getBean("carDao");
LeaseDao leaseDao = appContext.getBean("leaseDao");
這可能嗎? 我需要怎么做才能做到這一點?
接口不能擴展類,因此在這種情況下不能使用標記接口。 您可以上課。 以目前的形式,我認為您將無法創建GenericDAOImpl的bean,因此您需要創建擴展GenericDAOImpl的特定類的bean。 也就是說,您絕對可以將sessionfactory作為靜態字段拉到一個單獨的類中,進行連接並在DAO中使用靜態引用。 然后,您將不需要連接整個DAO,只需將實例創建為新的GenericDAOImpl()(或通過工廠)即可運行。 顯然,對於特定操作,您可以具有擴展GenericDAOImpl的實現。
HTH!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.