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?
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() {
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");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.