Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use entity manager in CDI extension

I want to write a CDI extension which loads some entities from database (which are in fact groovy scripts that implement a certain interface) and provide them as beans, so that it is possible to get all implementations of this interface injected by CDI. I think of sth. like the following:

public class ExtensionClass implements Extension {
  @Inject 
  EntityManager em;

  public void afterBeanDiscovery(@Observes final AfterBeanDiscovery event, final BeanManager manager) {
    Entity entity = em.find();
    //do sth with entity...
  }
}

When i try to inject the entity manager this way, it is null (which does not surprise me that much, i did not expect @Inject to work inside a CDI extension class).

Is it possible to get access to the entity manager inside a CDI extension somehow (via BeanManager for example)? Or do i have to access the db in another way?

like image 807
Daniel Nuss Avatar asked Jan 26 '26 21:01

Daniel Nuss


1 Answers

You have to create a producer for an EntityManager. However, I wouldn't recommend doing it inside of an extension, it's not portable (it may work on all implementations, but this would be one of those grey areas). Entities also need to be produced instead of letting the CDI container handle it. If you need to do something with the entities at the start of the application I recommend using @Startup from the EJB spec.

like image 191
LightGuard Avatar answered Jan 28 '26 15:01

LightGuard