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.
It is possible to do a self injection
. You need to use SessionContext
.
SessionContext sc = ...
sc.getBusinessObject(FooBean.class).processWithNewTransaction()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With