2014-10-19 97 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

相关问题