EJB3 bean可以“自我注入”吗?并通过EJB容器调用自己的方法? [英] Can an EJB3 bean "self inject" and call its own methods via EJB container?

查看:151
本文介绍了EJB3 bean可以“自我注入”吗?并通过EJB容器调用自己的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以自我注入EJB以便将本地方法作为bean方法调用?在某些情况下,这可能是有利的,例如,如果使用容器管理的交易,并且应该在新的交易中完成某些事情。

Is it possible to "self inject" an EJB in order to call local methods as bean methods? There are some cases where this could be favorable, for example if container managed transactions are used and something should be accomplished in a new transaction.

这是如何工作的一个例子:

An example how this could work:

Foo.java:

Foo.java:

@Local
public interface FoO {
    public void doSomething();
    public void processWithNewTransaction(); // this should actually be private
}

FooBean.java:

FooBean.java:

@Stateless
public class FooBean implements Foo {

    @EJB
    private Foo foo;

    public void doSomething() {
        ...
        foo.processWithNewTransaction();
        ...
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void processWithNewTransaction() {
        ...
    }
}

如果我提取 processWithNewTransaction()到另一个bean,它需要在接口中作为公共方法公开,即使它只应该由 FooBean 调用。 (同样的问题在于上面的代码,这就是接口定义中有注释的原因。)

If I extract processWithNewTransaction() to another bean, it would need to be exposed as a public method in the interface, even though it should be called only by FooBean. (The same issue is with my code above, that's why there is a comment in the interface definition.)

一种解决方案是切换到bean管理的事务。但是,这需要更改整个bean来管理自己的事务,并且会为所有方法添加大量的样板。

One solution would be to switch to bean managed transactions. However this would require changing the whole bean to manage its own transactions, and would add a lot of boiler plate to all methods.

推荐答案

更新:正如其他答案所述,这在技术上确实是可行的。请参阅 Csaba 迈克尔关于如何以及为什么它的工作尽管有无尽的递归。

Update: As noted by other answers, this is indeed technically possible. Please see the answers of Csaba and Michael on how and why it works despite the apparend endless recursion.

我不能给100%准确的答案,但我很确定这是不可能的。

I cannot give a 100% accurate answer but I'm pretty sure that this is not possible.

我是这么认为的,因为要将Foo bean注入Foo bean本身,容器最初必须创建他之后可以注入的Foo实例。但是为了创建它,他必须将一个已经存在的Foo实例注入到要创建的Foo中......这会导致无限递归。

I think so because for injecting the Foo bean into the Foo bean itself the container would initially have to create a Foo instance which he can inject afterwards. But to create this he has to inject an already existing instance of Foo into the Foo to be created... which leads to an infinite recursion.

如果你需要单独的事务我建议保持简单并创建两个独立的bean /接口。

If you need separate transactions I'd suggest to keep things easy and create two independend beans/interfaces.

这篇关于EJB3 bean可以“自我注入”吗?并通过EJB容器调用自己的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆