本文介紹了如何在Spring MVC攔截器中獲取方法執行流程的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想在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
建議可以實現這一點。
編寫將截獲的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方法花費350
方法com.est.service.TestService.getTest采用1954年
方法com.est.Controller.TestController.getTest采用3751
或者,可以編寫三個切入點和各自的Around
建議,每個攔截特定的包,以消除檢查控制器的if-else
部分
我已使用
測試了設置
Spring 4.3.2 Release
AspectJ 1.7.4
JDK 1.8
Tomcat 8.0
如果有任何問題,請在備注中告知。
這篇關于如何在Spring MVC攔截器中獲取方法執行流程的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,