[英]Create autowire capable Spring beans dynamically at runtime
我尝试动态初始化我的Hibernate DAO实例。
给出了什么:
GenericDaoImpl<T,PK extends Serializable>
) 通用工厂
@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:
尽管我强烈建议您使用Spring Data JPA之类的东西,但是配置错误(IMHO)。 代替使用@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 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.