简体   繁体   中英

Create autowire capable Spring beans dynamically at runtime

I try to initialize my Hibernate DAO instances dynamically.

What is given:

  • Generic 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)
  • Beans seem to be created, but as soon as I want to autowire I receive a Exception
  • Spring "3.2.4.RELEASE" Environment

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). Instead of using a @Configurable bean use a @Configuration bean which constructs the objects and which simply takes care of autowiring.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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