[英]Create autowire capable Spring beans dynamically at runtime
I try to initialize my Hibernate DAO instances dynamically. 我尝试动态初始化我的Hibernate DAO实例。
What is given: 给出了什么:
GenericDaoImpl<T,PK extends Serializable>
) 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();
}
}
}
Exception 例外
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:
Although I strongly recommend you use something like Spring Data JPA your configuration is wrong (IMHO). 尽管我强烈建议您使用Spring Data JPA之类的东西,但是配置错误(IMHO)。 Instead of using a
@Configurable
bean use a @Configuration
bean which constructs the objects and which simply takes care of autowiring. 代替使用
@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
}
But as mentioned instead of trying to hack together your own Generic Dao solution take a look at Spring Data JPA . 但是,正如前面提到的,与其尝试破解您自己的Generic Dao解决方案,不如看看Spring Data JPA 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.