Reputation: 1489
How to autowire a generic bean in spring?
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;
}
...
}
Now I want to autowired the DaoImpl like this:
@Autowired
GenericDaoImpl<XXXEntity> xxxEntityDao;
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>
But I doesn't work, How should I config it? or a good practice about generic Dao implement?
Upvotes: 0
Views: 1411
Reputation: 1489
There is an alternative way.
I change the GenericDaoImpl<T>
to a common class without Generic but use the generic in function
level, and the entityClass
can be configured in spring xml.
Upvotes: 0
Reputation: 2033
Work with your interfaces instead of implementations
Do not use @Transactional in your persistent layer as it is much more likely that it belongs to your service layer.
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;
Upvotes: 1