如何在春季自动接线通用bean [英] How to autowire a generic bean in spring
问题描述
如何在春季自动接线通用bean?
How to autowire a generic bean in spring?
我有一个dao工具,如下:
I have a dao implement as follows:
@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:
Now I want to autowired the DaoImpl like this:
@Autowired
GenericDaoImpl<XXXEntity> xxxEntityDao;
我在spring xml中进行配置:
I config in the 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工具的良好做法?
But I doesn't work, How should I config it? or a good practice about generic Dao implement?
推荐答案
使用您的界面而不是实现
Work with your interfaces instead of implementations
请勿在持久层中使用@Transactional,因为它很可能属于您的服务层.
Do not use @Transactional in your persistent layer as it is much more likely that it belongs to your service layer.
话虽如此,扩展通用的dao和autowire可能更有意义.例如:
Those being said, it might make more sense to extend the generic dao and autowire that. An example would be something like :
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
但是,如果您真的想以这种方式使用它,则必须声明一个限定符:
But if you really really want to use it that way you have to declare a qualifier :
@Autowired
@Qualifier("MyBean")
private ClassWithGeneric<MyBean> autowirable;
这篇关于如何在春季自动接线通用bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!