使用构造函数自动装配泛型类型 [Spring 4.2.5]

Autowiring generic types with constructor [Spring 4.2.5]

我是 Spring 的新手,正在尝试像本文 http://www.ibm.com/developerworks/library/j-genericdao/ 中那样实现通用 DAO。我有几个实体 - ConcreteEntity1 和 ConcreteEntity2。另外,我有 类

public interface GenericDao<T extends Serializable>  {
    public T get(long id);
    public List<T> get(String hql);
    public void remove(T persistentObject);
    public void add(T entity);
}

@Repository("hibGenericDao")
public class HibGenericDaoImpl<T extends Serializable> implements GenericDao<T> {

    @Autowired
    private SessionFactory sessionFactory;

    private Class<T> type;

    public HibGenericDaoImpl(Class<T> type) {
        this.type = type;
    }

    /** {@inheritDoc} */
    @Override
    public T get(long id) {
        T entity;
        try (Session session = sessionFactory.getCurrentSession()) {
            entity = session.get(type, id);
        }
        return entity;
    }

    /** {@inheritDoc} */
    @Override
    public List<T> get(String hql) {
        List<T> entityList;
        try (Session session = sessionFactory.getCurrentSession()) {
            Query query = session.createQuery(hql);
            entityList = query.list();
        }
        return entityList;
    }

    /** {@inheritDoc} */
    @Override
    public void remove(T persistentObject) {
        try (Session session = sessionFactory.getCurrentSession()) {
            session.delete(persistentObject);
        }
    }

    /** {@inheritDoc} */
    @Override
    public void add(T entity) {
        try (Session session = sessionFactory.getCurrentSession()) {
            session.saveOrUpdate(entity);
        }
    }
}

现在我正在尝试编写服务层,我想自动装配 HibGenericDaoImpl<ConcreteEntity1>,其中字段 type 包含 ConcreteEntity1.class。你能说一下没有XML如何执行吗?

用零参数构造函数替换您的构造函数。然后你可以使用 this link.

通过反射获得 T 类型

如果您已经在使用 spring,您可以使用 GenericTypeResolver utility class, as shown in this SO answer: How to get a class instance of generics type T

您应该可以执行以下操作:

 this.type = (Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), GenericDao.class);