2013-11-26 94 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