java – 将@Resource UserTransaction注入EJB Singleton bean是否安全

Q1:

我正在编写一个使用BMT的EJB Singleton bean,所以我需要在我的bean中使用UserTransaction.我想知道将ISRAN的@Resource UserTransaction注入我的EJB单例bean是非常安全的.我不知道容器是否会注入UserTransaction或NOT的代理.有人可以给我一些想法吗?谢谢!

Q2:

@Resource UserTransaction和sessionContext.getUserTransaction()之间有什么区别.它们是等价的吗?

最佳答案

I was wondering that IS IT SAFE to inject @Resource UserTransaction to my EJB singleton bean.

Singleton会话bean是ejb3.1 specification中定义的三个bean之一:无状态,有状态和单例.
 因此,对于Singleton,Container必须遵循与其他会话bean相同的合同.

合同说:

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?

对,他们是.这就是规范所说的:

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.

也许你的怀疑来自同一个Singleton实例可以由多个同时线程共享的事实,
它将共享相同的SessionContext实例.然而.这应该不是问题.
我使用条件表单,因为我没有尝试过,但除了可能出现的线程安全相关主题之外,请查看第117页的表格
其中明确指出必须支持使用UserTransaction方法

Table 3

Operations Allowed in the Methods of a Singleton Session Bean:

Bean-managed transaction demarcation:

SessionContext methods: UserTransaction methods

点赞