Hi, folks!

As I told earlier, I'm working on OpenJPA support of CDI injection on entity 
listeners.



The spec states that:



An entity listener is a noncontextual object.
In supporting injection into entity listeners, the persistence provider
must behave as if it carries out the following steps involving the use
of the CDI SPI. (See 
https://jakarta.ee/specifications/persistence/3.2/jakarta-persistence-spec-3.2.html#a19500
 ).

Obtain a BeanManager instance. (See 
https://jakarta.ee/specifications/persistence/3.2/jakarta-persistence-spec-3.2.html#a12802
 )


Create an AnnotatedType instance for the entity listener class.


Create an InjectionTarget instance for the annotated type.


Create a CreationalContext.


Instantiate the listener by calling the InjectionTarget produce method.


Inject the listener instance by calling the InjectionTarget inject method on 
the instance.


Invoke the PostConstruct callback, if any,
by calling the InjectionTarget postConstruct method on the instance.




When the listener instance is to be
destroyed, the persistence provider must behave as if it carries out the
following steps.


Call the InjectionTarget preDestroy method on the instance.


Call the InjectionTarget dispose method on the instance


Call the CreationalContext release method.




Persistence providers may optimize the steps
above, e.g. by avoiding calls to the actual CDI SPI and relying on
container-specific interfaces instead, as long as the outcome is the
same.


Entity listeners that do not make use of CDI
injection are stateless. The lifecycle of such entity listeners is
unspecified.



My first implementation was creating a CDI injected bean for each listener call 
(and it can be burdensome and have some performance penalty). Trying the same 
application using eclipselink, the behavior was different: it seems their 
contextual injected entity listeners are created only once and used for all JPA 
container life, so a @Dependent created bean is injected once and does not get 
updated in subsequent calls, even if it should. The common use case is the 
injection of a userId per request. There is a workarround for this behavior, 
though: the entity listener may use @Inject 
Instance<YourRequestOrDependentBean> to get current state.

Given the performance penalty, I'm switching the impl to behave as eclipselink 
behaves - cache the created listener, destroying it only when the container is 
shutdown. 

Do you agree?


Best regards,

Paulo

Reply via email to