简体   繁体   English

Spring IoC和通用接口类型的实现

[英]Spring IoC and Generic Interface Type Implementation

Originally based on this thread: 最初基于此线程:

Spring IoC and Generic Interface Type Spring IoC和通用接口类型

and this one 还有这个

Write Less DAOs with Spring Hibernate using Annotations 使用注释使用Spring Hibernate编写更少的DAO

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. 但是我想通过1 GenericDaoImpl(类似于上面的GenericDaoImpl)来实现细节,以避免为简单的CRUD编写重复的Impl。 (I would write custom Impl(s) for Entities which require more advanced DAO functionality.) (我将为需要更高级DAO功能的实体编写自定义Impl。)

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. 以目前的形式,我认为您将无法创建GenericDAOImpl的bean,因此您需要创建扩展GenericDAOImpl的特定类的bean。 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. 也就是说,您绝对可以将sessionfactory作为静态字段拉到一个单独的类中,进行连接并在DAO中使用静态引用。 Then, you wont need to wire the entire DAO, just create instances as new GenericDAOImpl() (or via a factory) and it will work. 然后,您将不需要连接整个DAO,只需将实例创建为新的GenericDAOImpl()(或通过工厂)即可运行。 Obviously, for specific operations, you can have implementations that extend GenericDAOImpl. 显然,对于特定操作,您可以具有扩展GenericDAOImpl的实现。

HTH! HTH!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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