在我的Java EE程序中,我想使用Interceptor进行日志记录.当我输入方法时,它很容易使用:
注释:
@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target({ METHOD, TYPE })
public @interface Logged {
}
拦截器:
@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();
}
}
我的班级使用拦截器:
public class MyClass {
@Logged
public void MyMethod() {
// do something
}
}
但是现在我想在离开MyMethod时做同样的事情.那可能吗 ?
解决方法:
AroundInvoke并不意味着特意进入 – 这意味着你“围绕调用”挂起它;它的名字恰如其分.那个proceed()调用就是你用拦截器包装的实际方法调用.因此,您当前在proceed()调用之前记录 – 如果您在proceed()调用之后添加日志,那么就是离开方法调用的点.
@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;
}
}