1

I need to execute a logic before every call in a stateless bean method.

Example:

class MyStatelessBean
{
   void myPreExecutionLogic()
   {
       System.out.println("pre method execution logic");
   }

   void method1()
   {
       System.out.println("method 1");
   }

   void method2()
   {
       System.out.println("method 2");
   }
}

There is a way of doing this using EJB? Registering some kind of listener or annotating the myPreExecutionLogic like @PreConstruct?

Wagner Paz
  • 11
  • 1

2 Answers2

2

If you are using EJB3, you can use Interceptors and @AroundInvoke

Set up an interceptor class with the @AroundInvoke annotation

public class MyInterceptor {

    @AroundInvoke
    public Object doSomethingBefore(InvocationContext inv) {
         // Do your stuff here.
         return inv.proceed();
    }
}

Then annotate your ejb methods with the class name

public class MyStatelessBean {

       @Interceptors ( {MyInterceptor.class} )
       public void myMethod1() {
Shai Rippel
  • 428
  • 1
  • 4
  • 12
Kal
  • 24,724
  • 7
  • 65
  • 65
  • hum, ok. I read the [article](http://weblogs.java.net/blog/meeraj/archive/2006/01/interceptors_wi.html) that you mentioned and conclude that the example below will solve part of my problem. 'class MyStatelessBean { @AroundInvoke void myPreExecutionLogic(InvocationContext invocationContext)
    { System.out.println("pre method execution logic");
    } void method1() { System.out.println("method 1"); } }' There is a way of doing this in a abstract super class? I need that all the subclasses methods to be intercepted.
    – Wagner Paz Feb 23 '12 at 16:56
  • 1
    @Wagner -- Yes. You can define your interceptor on the super class itself. Then all the subclass methods will be intercepted. – Kal Feb 23 '12 at 19:36
1

A little variation of Kal's answer, I managed to make the method in the same class as the example declared (reminds me of junits @Before).

Also don't forget the "throws Exception" of the method signature for exceptions thrown from the actual method call inside ctx.proceed()

class MyStatelessBean
{

    @AroundInvoke
    public Object myPreExecutionLogic(InvocationContext ctx) throws Exception{
        System.out.println("pre method execution logic");

        return ctx.proceed();
    }

   void method1()
   {
       System.out.println("method 1");
   }

   void method2()
   {
       System.out.println("method 2");
   }
}
Shai Rippel
  • 428
  • 1
  • 4
  • 12