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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With