I have been struggling with this issue for a while and have browsed a lot of articles, but couldnt figure out the solution. Appreciate your help with the issue below.
I need to be able to autowire the EntityManager in the service class, but throws an exception. The default constructor probably has issues because of type erasure and so I tried using a constructor with parameters to set the Type. How do I autowire EntityManager of type User?
public interface IEntityManager<T extends IDomain<ID>, ID extends Serializable> {
T findById(ID id, boolean lock);
T save(T entity);
void delete(T entity);
}
public class EntityManager<T extends IDomain<ID>, ID extends Serializable>
implements IEntityManager<T, ID> {
private Class<T> entity;
@Autowired(required=true)
private SessionFactory sessionFactory;
/*
@SuppressWarnings("unchecked")
public EntityManager() {
this.entity = (Class<T>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
} */
@Autowired(required=true)
public EntityManager(Class<T> entity) {
this.entity = entity;
}
}
@Service("UserService")
@Transactional
public class UserServiceImpl implements IUserService {
@Autowired
EntityManager<User, Integer> entityManager;
}
Here is the exception:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserService': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.test.dummy.persistence.manager.EntityManager com.test.dummy.service.UserServiceImpl.entityManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.test.dummy.persistence.manager.EntityManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)