[英]How to autowire a generic bean in spring
如何在春季自动接线通用bean?
我有一个dao工具,如下所示:
@Transactional
public class GenericDaoImpl<T> implements IGenericDao<T>
{
private Class<T> entityClass;
@Autowired
private SessionFactory sessionFactory;
public GenericDaoImpl(Class<T> clazz) {
this.entityClass = clazz;
}
...
}
现在,我想像这样自动连接DaoImpl:
@Autowired
GenericDaoImpl<XXXEntity> xxxEntityDao;
我在spring xml中配置:
<bean id="xxxEntityDao" class="XXX.GenericDaoImpl">
<constructor-arg name="clazz">
<value>xxx.dao.model.xxxEntity</value>
</constructor-arg>
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
但是我不工作,应该如何配置? 或关于通用Dao工具的良好实践?
使用您的界面而不是实现
不要在持久层中使用@Transactional,因为它很可能属于您的服务层。
话虽这么说,扩展通用的dao和autowire可能更有意义。 例如:
public interface UserDao extends GenericDao<User> {
User getUsersByNameAndSurname(String name, String surname);
... // More business related methods
}
public class UserDaoImpl implements UserDao {
User getUsersByNameAndSurname(String name, String surname);
{
... // Implementations of methods beyond the capabilities of a generic dao
}
...
}
@Autowired
private UserDao userDao; // Now use directly the dao you need
但是,如果您真的想以这种方式使用它,则必须声明一个限定符:
@Autowired
@Qualifier("MyBean")
private ClassWithGeneric<MyBean> autowirable;
还有另一种方法。
我将GenericDaoImpl<T>
更改为一个没有Generic的通用类,但在功能级别使用了generic,并且可以在spring xml中配置entityClass
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.