Issue
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?
Solution
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;
Answered By - Pumpkin
Answer Checked By - Clifford M. (JavaFixing Volunteer)