怎么在Spring MVC拦截器中获取方法执行流程

原学程将引见若何在Spring MVC拦阻器中夺取办法履行过程的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。

怎么在Spring MVC拦截器中获取方法执行流程 教程 第1张

成绩描写

我想在Spring MVC项目中取得完全的履行过程和它们的履行时光。

public class MetricsInterceptor extends HandlerInterceptorAdapter {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
 if (handler instanceof HandlerMethod) {
  HandlerMethod hm = (HandlerMethod) handler;
  Method method = hm.getMethod();
  if (method.getDeclaringClass().isAnnotationPresent(Controller.class)) {
if (method.isAnnotationPresent(Metrics.class)) {
// System.out.println(method.getAnnotation(Metrics.class).value());
 System.out.println(method.getName());
}
  }
 }
 return super.preHandle(request, response, handler);
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
 super.postHandle(request, response, handler, modelAndView);
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
 super.afterCompletion(request, response, handler, ex);
}

}

我应用@Metrics正文夺取掌握器类以及办法,以记载多少个办法的器量。我想要的是取得每一个办法所消费的时光的全部办法履行过程(掌握器-->办事-->DAO)。有甚么方法在postHandle()或者AfterCompletion()中夺取该信息。请提出修议。

推举谜底

应用Spring AOPAround修议不妨完成这1面。

编辑将截获的pointcut

    包及其子包中大众办法的一切履行

    属于

    的包及其子包

      掌握器层

      办事层(可选仅限于特定办事)

      DAO层

而后写下,以下

@Component
@Aspect
public class TraceAdvice {

 @Around("execution(* com.test..*(..))  &&" + " (within(com.test.controller..*) || "
  + "(within(com.test.service..*) && this(com.test.service.TestService)) || " + "within(com.test.dao..*))")
 public Object traceCall(ProceedingJoinPoint pjp) throws Throwable {
  /* This will hold our execution details in reverse order 
* i.e. last method invoked would appear first.
* Key = Full qualified name of method
* Value = Execution time in ms
*/
  Map<String, Long> trace = null;
  Signature sig = pjp.getSignature();
  // Get hold of current request
  HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  // check if we are in controller (I used RestController modify it if Controller is required instead) 
  boolean isController = sig.getDeclaringType().isAnnotationPresent(RestController.class);
  if (isController) {
// set the request attributte if we are in controller
trace = new LinkedHashMap<>();
req.setAttribute("trace", trace);
  } else {
// if its not controller then read from request atributte
trace = (Map<String, Long>) req.getAttribute("trace");
  }
  Object result = null;
  StopWatch watch = new StopWatch();
  try {
// start the timer and invoke the advised method
watch.start();
result = pjp.proceed();
  } finally {
// stop the timer 
watch.stop();
String methodName = sig.getDeclaringTypeName() + "." + sig.getName();
// make entry for the method name with time taken
trace.put(methodName, watch.getTotalTimeMillis());
if (isController) {
 // since controller method is exit point print the execution trace
 trace.entrySet().forEach(entry -> {
  System.out.println("Method " + entry.getKey() + " took " + String.valueOf(entry.getValue()));
 });
}
  }
  return result;
 }
}

在停止需要的设置装备摆设后,应以下所示

com.est.dao.TestDAO.getTest办法消费三五0

办法com.est.service.TestService.getTest采取一九五四年

办法com.est.Controller.TestController.getTest采取三七五一

我已应用

尝试了树立

    Spring 四.三.二 Release

    AspectJ 一.七.四

    JDK 一.8

    Tomcat 8.0

假如有所有成绩,请在备注中告诉。

佳了闭于怎样在Spring MVC拦阻器中夺取办法履行过程的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。