2013-11-26 40 views
0

我尝试动态初始化我的Hibernate DAO实例。在运行时动态创建支持autowire的Spring bean

什么给出:

  • 通用DAO(GenericDaoImpl<T,PK extends Serializable>
  • DAO厂,应在包中每个模型类创建一个通用的DAO实例(我尝试与反思的东西)
  • 豆类似乎要创建,但只要我想自动装配我收到一个异常
  • 春“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(); 
     } 
    } 

} 

异常

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

为什么?为什么重新发明Spring Data JPA已经发明的轮子? –

回答

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 
} 

但是如前所述,而不是试图破解了一下自己的通用解决方案道看看Spring Data JPA