2011-11-24 93 views
0

原來在此基礎上螺紋:的Spring IoC和泛型接口類型,實現

Spring IoC and Generic Interface Type

而這一次

Write Less DAOs with Spring Hibernate using Annotations

我不知道如何處理實施前的想法。可以說我有

@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); 
    } 

} 

而我是O.K.具有標記接口:

public interface CarDao extends GenericDao<Car> {} 
public interface LeaseDao extends GenericDao<Lease> {} 

但我想通過1個GenericDaoImpl漏斗實施細則(像上面的GenericDaoImpl),以避免書寫複製默認地將Impl(個),簡單的CRUD。 (我會寫自定義默認地將Impl(個),這需要更先進的DAO功能實體。)

所以後來終於在我的控制,我可以這樣做:

CarDao carDao = appContext.getBean("carDao"); 
LeaseDao leaseDao = appContext.getBean("leaseDao");  

這可能嗎?我需要做什麼才能做到這一點?

+2

難道你不能只創建兩個類:'@Repository CarDaoImpl extends GenericDaoImpl '和'@Repository LeaseDaoImpl extends GenericDaoImpl '。因此所有的實現細節都在父類中,或者我錯過了什麼? – matsev

+0

不知道爲什麼我沒有想到昨天。 – sloven

回答

1

接口不能擴展類,因此在這種情況下不能使用標記接口。你可以上課。以目前的形式,我不認爲你能夠創建GenericDAOImpl的bean,所以你需要創建那些擴展GenericDAOImpl的特定類。也就是說,你完全可以將sessionfactory作爲一個靜態字段放入一個單獨的類中,並將它連線並使用DAO中的靜態引用。然後,您不需要連線整個DAO,只需創建實例作爲新的GenericDAOImpl()(或通過工廠),它就可以工作。顯然,對於特定的操作,您可以擁有擴展GenericDAOImpl的實現。

HTH!