2014-10-19 195 views
1

我正在使用Spring + Jpa,並且我想讓EntityManager進入我的@Configuration類。Spring - 從@Configuration獲得EntityManager類

現在我的課是這樣的:

@Configuration 
@PropertySource("classpath:base.properties") 
public class Config { 
    private static final Logger log = Logger.getLogger(Config.class); 

    @Bean 
    public SpringContextManager contextManager() { 
     return new SpringContextManager(new DefaultApplication()); 
    } 

    @Bean(initMethod = "start", destroyMethod = "stop") 
    public ServerSession serverSession() throws Exception {  
     try { 
      ServerSession serverSession = new ServerSession(urlGateway, useSsl, hostGateway, portGateway); 
      serverSession.setDefaultTimeToLive(5000); 
      return serverSession; 
     } catch (Throwable e) { 
      log.error("", e); 
      return null; 
     } 
    } 



@Bean 
    public PluginManager pluginManager() { 
     PluginManager pluginManager = new PluginManager(); 
     ThreadLocalManager.set(pluginManager); 
    return pluginManager; 
    } 

我知道,我不能添加到@PersistenceContext類@Configuration,所以我不知道如何在這一點上獲得的EntityManager。

這樣做的目標是讓應用程序啓動時使用entityManager,因爲我需要將它設置爲一個ThreadLocal類(我需要此類來使用JPA entitylistener中的entityManager,其中persistenceContext注入不起作用)。

現在我從@Service註釋的服務中獲取entityManager,但將此設置變爲@Configuration類會更乾淨。似乎更乾淨。

感謝您的幫助。

+0

如果您需要它在偵聽器中,那麼只需在偵聽器中進行查找即可。此外,如果這是一個常規的春季聽衆注射應該只是工作。 – 2014-10-19 17:19:19

+0

你能舉個例子嗎?用簡單的@inject不起作用。謝謝 – drenda 2014-10-19 20:34:31

回答

0

我找到了一個很好的例子來解決我的問題。這是本教程的鏈接:link