With @AroundInvoke
The
@AroundInvoke annotated method, will describe a Bean's method as a Business interface interceptor.
In our case, all business interface methods will be intercepted by the 'trace' method.
@AroundInvoke
private Object trace(InvocationContext ic) throws Exception {
System.out.println("Intercepted method : " + ic.getMethod().getName());
return ic.proceed();
}The trace interceptor simply prints the method name before delegating the call continuation.
Output on the server side :
INFO: Before invoking on implementor
Intercepted method : sayHi
Executing operation sayHi
With @Interceptors
Add the
@Interceptors on the Bean, specifying the Class that hold the interceptor Method (annotated with
@AroundInvoke) :
@Stateless
@Local(ISayHi.class)
@WebService(name="Greeter",
serviceName="SOAPService",
targetNamespace="http://objectweb.org/greeter",
wsdlLocation="META-INF/wsdl/greeter.wsdl")
@PortComponent(urlPattern="/greeter")
@Interceptors(GreeterInterceptor.class)
public class Greeter implements IGreeter, ISayHi {
…
}
|
The @Interceptors annotation is used to declare both external method interceptors (@AroundInvoke) and external lifecyle callbacks(@PostConstruct, ...). |
The GreeterInterceptor class :
package org.objectweb.easybeans.examples.celtix;import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;/**
* This class intercepts Business interfaces methods.
* @author Guillaume Sauthier
*/
public class GreeterInterceptor { /**
* Invocation counter
*/
private int counter = 0; /**
* Count the invocations of a bean.
* @param ic InvocationContext
* @return proceeded method
* @throws Exception if something wrong occurs.
*/
@AroundInvoke
public Object count(InvocationContext ic) throws Exception { synchronized(this) {
counter++;
System.out.println("Method '" + ic.getMethod().getName()
+ "' invoked " + counter + " times.");
return ic.proceed();
}
}
}The GreeterInterceptor class is a
simple POJO that count invocations of a method.
Output (the WebServices is executed 2 times) :
INFO: Before invoking on implementor
Method 'sayHi' invoked 1 times.
Intercepted method : sayHi
Executing operation sayHi...INFO: Before invoking on implementor
Method 'sayHi' invoked 2 times.
Intercepted method : sayHi
Executing operation sayHi
As you can see EJB3 Interception mechanism is still working very well when mixed with
JAX-WS 2.0 WebServices.