I was wondering that IS IT SAFE to inject @Resource UserTransaction to my EJB singleton bean.
A Singleton session bean is one of the three beans defined in the ejb3.1 specification: Stateless, Stateful and Singleton.
Therefore, with Singleton, the Container must follow the same contract as other session beans.
The contract says:
4.3.3 The SessionContext Interface.
If the bean specifies a dependency on the SessionContext interface.., the container must provide the session
bean instance with a SessionContext. This gives the session bean instance access to the instance’s context maintained by the container.
.
What are difference between @Resource UserTransaction and sessionContext.getUserTransaction(). Are they equivalent?
Yes, they are. This what the specification says:
4.3.2 Dependency Injection.
Under the EJB 3.1 API, the bean class may acquire the SessionContext interface through dependency injection without having to implement the SessionBean interface. In this case,the Resource annotation (or resource-env-ref deployment descriptor element) is used to denote the bean’s dependency on the SessionContext.
Maybe your doubts comes from the fact that the same Singleton instance can be shared by several simultaneous threads,
which will share the same SessionContext instance. However. this shouldn't be a problem.
I use the conditional form because I have not tried it, but beyond the thread-safe related topic that can arise, take a look to the table on page 117
where explicitly is indicated that the use of UserTransaction method must be supported
Table 3
Operations Allowed in the Methods of a Singleton Session Bean:
Bean-managed transaction demarcation:
SessionContext methods: UserTransaction methods