Alex Rivera | Logout

Can an EJB3 bean "self inject" and call its own methods via EJB container?

Asked 2009-03-11T08:00:54.050
14

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:

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

FooBean.java:

@Stateless
public class FooBean implements Foo {

    @EJB
    private Foo foo;

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

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

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.)

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.

Edit
Report

1 Answer

11

Self injection of a EJB is indeed possible. The reason why an infinite recursion won't happen in this case is pretty simple: the container doesn't inject an actual bean instance from the pool. Instead, it injects a proxy object. When you call a method on the injected proxy (foo), the container gets a bean instance from its pool or creates one, if there are no available instances.

answered 2012-09-04T01:24:05.123

Your Answer