2014-03-04 33 views
0

具有這種通用的DAO定義如何以編程方式實例化注入EntityManager?

@Repository 
public class GenericService<T> implements IGenericService<T> { 
    @PersistenceContext(unitName="mgrUnit", name="mgrEMF") 
    @Qualifier(value = "mgrEMF") 
    public void setEm(EntityManager em) {  
     this.em = em;  
     util = em.getEntityManagerFactory().getPersistenceUnitUtil();  
    } 
} 

並具有大量的實體,我想automatiqualy實例化DAO,後端豆類基本表像(區,EmployeSpeciality ...)

對於這個bean的註冊和實例很簡單,但是DAO呢? 我必須精確的說,在我的情況下,EntityManager取決於服務,我有一個多個數據庫連接。

我讀這篇文章,但honnestly它看起來複雜得多

http://doanduyhai.wordpress.com/2011/11/20/spring-transactional-explained/

有一個簡單的辦法做到這一點?

OK,使用

AutowireCapableBeanFactory beanFactory = 
FacesUtils.getWebappContext().getAutowireCapableBeanFactory(); 
beanFactory.autowireBean(obj); 

它解決了問題的一半,這個Bean EMF被正確注射,但豆不registred(我必須重新實例化它每次我需要時間),這是因爲beanFactory不包含Bean定義,所以如何添加它?

NB:我知道puting在應用程序映射對象可以保持DAO訪問的,但它不是一個嚴肅的解決方案

FacesContext.getCurrentInstance().getExternalContext(). 
      getApplicationMap().put(serviceName, service); 

回答

0
IGenericService service = (IGenericService) ContextManager.findBean(serviceName);  
if (service==null && !FacesUtils.getWebappContext().getBeanFactory(). 
      containsBeanDefinition(serviceName)){ 

    service = new ErpGenericService(clazz); 
    AutowireCapableBeanFactory beanFactory = FacesUtils.getWebappContext(). 
              getAutowireCapableBeanFactory(); 
    beanFactory.autowireBean(service); 
    //Applying transactional proxies 
    service = (IGenericService) beanFactory.applyBeanPostProcessorsAfterInitialization(service, serviceName); 
    FacesUtils.getWebappContext().getBeanFactory(). 
        registerSingleton(serviceName, service);      

} 
相關問題