简体   繁体   中英

Spring IoC and Generic Interface Type Implementation

Originally based on this thread:

Spring IoC and Generic Interface Type

and this one

Write Less DAOs with Spring Hibernate using Annotations

I'm wondering how to approach implementation of the former's idea. Lets say I've got

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

 }

and I am OK with having marker interfaces:

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

But I want to funnel the implementation details through 1 GenericDaoImpl (something like above's GenericDaoImpl), to avoid writing duplicate Impl(s) for simple CRUD. (I would write custom Impl(s) for Entities which require more advanced DAO functionality.)

So then eventually in my controller I can do:

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

Is this possible? What would I need to do to achieve this?

interfaces can not extend classes so marker interfaces can not be used in this case. you can have classes though. in its current form, I dont think you'll be able to create beans of GenericDAOImpl so you would need to create those of specific classes that extend GenericDAOImpl. That said, you can definitely pull out sessionfactory into a separate class as a static field, have it wired and use the static reference in the DAO. Then, you wont need to wire the entire DAO, just create instances as new GenericDAOImpl() (or via a factory) and it will work. Obviously, for specific operations, you can have implementations that extend GenericDAOImpl.

HTH!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM