In my Java EE program I want to use Interceptor for logging purpose. It's easy to use when I'm entering a method :
The annotation :
@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target({ METHOD, TYPE })
public @interface Logged {
}
The interceptor :
@Logged
@Interceptor
public class LoggedInterceptor implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
private Logger logger;
@AroundInvoke
public Object logMethodEntry(InvocationContext invocationContext) throws Exception {
logger.info("Entering method: "
+ invocationContext.getMethod().getName() + " in class "
+ invocationContext.getMethod().getDeclaringClass().getName());
return invocationContext.proceed();
}
}
My class using the interceptor :
public class MyClass {
@Logged
public void MyMethod() {
// do something
}
}
But now I want to do same thing when I'm leaving MyMethod. Is that possible ?
Interceptors are used in conjunction with Java EE managed classes to allow developers to invoke interceptor methods on an associated target class, in conjunction with method invocations or lifecycle events. Common uses of interceptors are logging, auditing, and profiling.
A Default interceptor is an interceptor that is invoked whenever a business method is invoked on any bean within the deployment.
Annotation Type AroundInvokeDefines an interceptor method that interposes on business methods. May be applied to any non-final, non-static method with a single parameter of type InvocationContext and return type Object of the target class (or superclass) or of any interceptor class.
AroundInvoke does not imply specifically entering - it implies that you hang it "around the invocation"; its name is aptly chosen. That proceed() call that is in there is the actual method invocation you are wrapping with the interceptor. As such you currently log BEFORE the proceed() call - if you add a log AFTER the proceed() invocation, that is the point of leaving the method invocation.
@Logged
@Interceptor
public class LoggedInterceptor implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
private Logger logger;
@AroundInvoke
public Object logMethodCall(InvocationContext invocationContext) throws Exception {
logger.info("Entering method: "
+ invocationContext.getMethod().getName() + " in class "
+ invocationContext.getMethod().getDeclaringClass().getName());
Object ret = invocationContext.proceed();
logger.info("Left method: "
+ invocationContext.getMethod().getName() + " in class "
+ invocationContext.getMethod().getDeclaringClass().getName());
return ret;
}
}
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