[英]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.