che*_*1k4 3 java interceptor jakarta-ee
在我的Java EE程序中,我想使用Interceptor进行日志记录。当我输入一个方法时它很容易使用:
注释:
@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target({ METHOD, TYPE })
public @interface Logged {
}
Run Code Online (Sandbox Code Playgroud)
拦截器:
@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();
}
}
Run Code Online (Sandbox Code Playgroud)
我的班级使用拦截器:
public class MyClass {
@Logged
public void MyMethod() {
// do something
}
}
Run Code Online (Sandbox Code Playgroud)
但是现在我想在离开MyMethod时做同样的事情。那可能吗 ?
AroundInvoke 并不意味着特别进入——它意味着你把它挂在“调用周围”;它的名字是恰当地选择的。那里的proceed() 调用是您使用拦截器包装的实际方法调用。因此,您当前在procedure() 调用之前进行记录——如果您在procedure() 调用之后添加日志,那就是离开方法调用的点。
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3278 次 |
| 最近记录: |