在运行时动态创建支持autowire的Spring bean

时间:2013-11-26 08:55:09

标签: java spring spring-mvc javabeans autowired

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

给出了什么:

  • 通用DAO(GenericDaoImpl<T,PK extends Serializable>
  • DAO Factory,它应该为包中的每个模型类创建一个通用的DAO实例(我尝试使用反射)
  • Beans似乎被创建了,但是一旦我想要自动装配我就会收到异常
  • 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();
        }
    }

}

异常

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: 

1 个答案:

答案 0 :(得分:1)

虽然我强烈建议您使用类似Spring Data JPA的内容,但配置错误(恕我直言)。而不是使用@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