adam bien's blog

How To Self-Invoke EJB 3.x with(out) "this" 📎

EJB 3.1 are "POJOs with built-in aspects". You get transactions, security, concurrency and monitoring for free with only negligible overhead and without any XML configuration. The aspects, however, can only work in case the container is able to intercept the calls.
Call interception works if the injected (or looked-up) instances are used. this keyword does not work--the call is obviously not intercepted. To get "this with aspects" you will have to use an injected (or looked-up) instance or use the SessionContext#getBusinessObject method:


@Named
@Stateless
public class Hack {
    
    @Resource
    SessionContext sc;
    
    Hack me;
    
    @PostConstruct
    public void init(){
        this.me = this.sc.getBusinessObject(Hack.class);
    }

    @TransactionAttribute(value= TransactionAttributeType.NOT_SUPPORTED)
    public String boundaryMethodWithoutAspects(){
        this.expectsException();
        return "...just an ordinary call";
    }
    
    @TransactionAttribute(value= TransactionAttributeType.NOT_SUPPORTED)
    public String boundaryMethodWithAspects(){
        try{
            this.me.expectsException();
            return "...exception expected :-(";
        }catch(EJBTransactionRequiredException e){
            return "Works! : " + e;
        }
    }
    
    @TransactionAttribute(value= TransactionAttributeType.MANDATORY)
    public void expectsException(){
        System.out.println("Should not appear in the log");
    }
}


The execution of the boundary… methods leads to the following output:
boundaryMethodWithoutAspects(): Without aspects: ...just an ordinary call
boundaryMethodWithAspects(): With aspects: Works! : javax.ejb.EJBTransactionRequiredException

EJB 3 Self-invocation with aspects should not be considered as a best practice. Instead of using the "pattern" described here, you should factor out the method into another bean and introduce a Control

The sample project "SelfInvokingEJB" was pushed into:http://kenai.com/projects/javaee-patterns/