繁体   English   中英

在运行时动态创建具有自动装配功能的Spring Bean

[英]Create autowire capable Spring beans dynamically at runtime

我尝试动态初始化我的Hibernate DAO实例。

给出了什么:

  • 通用DAO( GenericDaoImpl<T,PK extends Serializable>
  • DAO Factory,应该为包中的每个模型类创建一个通用DAO实例(我尝试了一些反射)
  • 似乎已经创建了Bean,但是一旦我想自动装配,就会收到一个异常
  • 春季“ 3.2.4.RELEASE”环境

通用工厂

@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM