我尝试动态初始化我的Hibernate DAO实例。
给出了什么:
GenericDaoImpl<T,PK extends Serializable>
)GenericDaoFactory
@Configurable
public class GenericDaoFactory {
@Autowired private AutowireCapableBeanFactory beanFactory;
@Autowired private SessionFactory sessionFactory;
@PostConstruct
private void createDynamicDaoBean() {
try {
// Example for employee variant
GenericDaoImpl<Employee, Integer> employeeDao = new GenericDaoImpl<Employee, Integer>(Employee.class, sessionFactory);
beanFactory.autowireBean(employeeDao);
beanFactory.initializeBean(employeeDao, "employeeDao");
} catch(Exception e) {
e.getMessage();
}
}
}
异常
Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com..test.dao.GenericDaoImpl com.test.service.EmployeeService.employeeDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
答案 0 :(得分:1)
虽然我强烈建议您使用类似Spring Data JPA的内容,但配置错误(恕我直言)。而不是使用@Configurable
bean使用构造对象的@Configuration
bean,它只需要处理自动装配。
@Configuration
public class DaoConfiguration {
private SessionFactory sf;
@Bean
public GenericDao<Employee, Integer> employeeDao() {
return new GenericDaoImpl<Employee, Integer>(Employee.class, sessionFactory);
}
// Other daos
}
但是如上所述,不要试图破解你自己的Generic Dao解决方案,而是看看Spring Data JPA。