我想知道是否可以在生产中的java ee应用程序的方法中记录所有指令的执行.这应该提供属性的值以及指令是否已正确执行.
我知道像glassfish这样的应用程序服务器提供的基本日志,但我希望在以前的任何时候都能获得具有变量值的详细执行历史记录.
最好的祝福
你所描述的内容被@AroundInvoke拦截器轻易覆盖,拦截器是CDI支持的少数拦截器之一.它仍然基于AOP方法,类似于AspectJ的另一个答案.记录是说明这种拦截器的首选示例,所以让我们考虑以下内容MethodLogger.
定义一个类MethodLogger.这是您将委派实际日志记录的类.您也可以在此课程中访问您正在查找的信息(方法名称,执行完成,参数等)
public class MethodLogger{
private Logger logger = Logger.getLogger("com.you.MethodLogger");
@AroundInvoke
public Object logIt(InvocationContext iCtxt) throws Exception{
logger.entering(iCtxt.getTarget().toString(),iCtxt.getMethod().getName(),iCtxt.getParameters());
try{
return iCtxt.proceed(); //important! otherwise, method invocation doesn't continue
}
catch(Exception ex){
//do whatever you want whenever an exception occurs during this process
}
finally{
logger.exiting(iCtxt.getTarget().toString(),iCtxt.getMethod().getName());
}
}
}
Run Code Online (Sandbox Code Playgroud)将拦截器应用于EJB
@Stateless
@Interceptors(MethodLogger.class) //apply this annotation to intercept every method call on this EJB
public class YourEJB{
@Interceptors(MethodLogger.class) // apply here if you want only a specific method to be tracked
public void doSomething();
@ExcludeClassInterceptors //apply this to stop the interceptor from affecting this method
public void doSomethingElse();
}
Run Code Online (Sandbox Code Playgroud)从EJB 3.1,您还可以选择指定全局拦截器.无论注释使用如何,如此定义的拦截器将应用于应用程序中的所有EJB.所以在ejb-jar.xml中:
<assembly-descriptor>
<interceptor-binding>
<ejb-name>*</ejb-name>
<interceptor-class>com.you.MethodLogger</interceptor-class>
</interceptor-binding>
</assembly-descriptor>
Run Code Online (Sandbox Code Playgroud)
进一步阅读