tags:

views:

462

answers:

2

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.

+1  A: 

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

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.

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

Kosi2801
Agree! Recursiv definition of session beans is not a good idea.
Timo
+1  A: 

Interesting question. I never create a method with a different transaction attribute in the same bean, that is, this begs for refactoring. This usually makes it hard to spot bugs in the application when it evolves.

EDIT: fixed typos

Antonio