Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

ejb-3.0

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.

like image 909
tputkonen Avatar asked Mar 11 '09 08:03

tputkonen


1 Answers

It is possible to do a self injection. You need to use SessionContext.

SessionContext sc = ...
sc.getBusinessObject(FooBean.class).processWithNewTransaction()
like image 113
michael nesterenko Avatar answered Sep 30 '22 02:09

michael nesterenko