简体   繁体   English

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

[英]Create autowire capable Spring beans dynamically at runtime

I try to initialize my Hibernate DAO instances dynamically. 我尝试动态初始化我的Hibernate DAO实例。

What is given: 给出了什么:

  • Generic DAO ( GenericDaoImpl<T,PK extends Serializable> ) 通用DAO( GenericDaoImpl<T,PK extends Serializable>
  • DAO Factory, which should create a Generic DAO instance for each model class in package (I try something with reflection) DAO Factory,应该为包中的每个模型类创建一个通用DAO实例(我尝试了一些反射)
  • Beans seem to be created, but as soon as I want to autowire I receive a Exception 似乎已经创建了Bean,但是一旦我想自动装配,就会收到一个异常
  • Spring "3.2.4.RELEASE" Environment 春季“ 3.2.4.RELEASE”环境

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.

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