1
votes

I'm using Spring + Jpa and I'd like to have EntityManager into my @Configuration class.

Now my class is something like this:

 @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;
    }

I know that I can't add @PersistenceContext to @Configuration class, so I don't know how to get entityManager at this point.

The goal of this is have entityManager asap the app start because I need to set it into a ThreadLocal class ( i need this class to use entityManager inside a JPA entitylistener where inject of persistenceContext don't work).

Now I'm getting the entityManager from a service annotated with @Service but it would be cleaner to made this settings into @Configuration class. Seems more clean.

Thanks for your help.

1
If you need it inside a listener then just do a lookup in the listener. Also if it is a regular spring listener injection should just work. - M. Deinum
Can you provide an example please? With simple @inject don't work. Thanks - drenda

1 Answers

0
votes

I found a nice example to solve my problem. This is the link of the tutorial: link