Tunguska
Tunguska

Reputation: 1205

Create autowire capable Spring beans dynamically at runtime

I try to initialize my Hibernate DAO instances dynamically.

What is given:

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: 

Upvotes: 0

Views: 2007

Answers (1)

M. Deinum
M. Deinum

Reputation: 124526

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.

Upvotes: 1

Related Questions