gpt4 book ai didi

java - 离开方法时使用拦截器

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:42:33 25 4
gpt4 key购买 nike

在我的 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();

}
}

我的类(class)使用拦截器:

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;
}
}

关于java - 离开方法时使用拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33297793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com