在使用 AOP 环绕通知做日志处理的时候,发现 @Around 方法执行了两次,虽然这里环绕通知本来就会执行两次,但是正常情况下是在切点方法前执行一次,切点方法后执行一次,但是实际情况却是,切点方法前执行两次,切点方法后执行两次。
文字不好理解,还是写一下代码:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@Around ( "logPointCut()" ) public Object doAround(ProceedingJoinPoint pjp) throws Throwable { logger.debug( "==========Request log==========" ); long startTime = System.currentTimeMillis(); Object ob = pjp.proceed(); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); //JSONObject ipInfo = JSONObject.fromObject(URLDecoder.decode(WebUtils.getCookie(request,"IP_INFO").getValue(),"utf-8")); //logger.debug("IP: {}", ipInfo.get("ip")); //logger.debug("CITY {}", ipInfo.get("city")); logger.debug( "IP: {}" , BlogUtil.getClientIpAddr(request)); logger.debug( "REQUEST_URL: {}" , request.getRequestURL().toString()); logger.debug( "HTTP_METHOD: {}" , request.getMethod()); logger.debug( "CLASS_METHOD: {}" , pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName()); //logger.info("参数 : " + Arrays.toString(pjp.getArgs())); logger.debug( "USE_TIME: {}" , System.currentTimeMillis() - startTime); logger.debug( "==========Request log end==========" ); return ob; } |
然后刷新一下页面,得到的日志如下:
可以看到,虽然只刷新了一次,但是却输出了两次日志,是不应该的。然后通过断点调试发现,是因为在 Controller 中使用了 @ModelAttribute
|
1 2 3 4 5 |
@ModelAttribute public void counter(Model model) { counter.setCount(counter.getCount() + 1 ); model.addAttribute( "count" , counter.getCount()); } |
@ModelAttribute 注解的方法会在 Controller 方法执行之前执行一次,并且我将它放在了 Controller 中,并且拦截的是所有 Controller 中的方法,
这样就导致了:
1、首先页面请求到 Controller ,执行 @ModelAttribute 标注的方法,此时会被 AOP 拦截到一次。
2、执行完 @ModelAttribute 标注的方法后,执行 @RequestMapping 标注的方法,又被 AOP 拦截到一次。
所以,会有两次日志输出。
解决办法:
1、将 Controller 中的 @ModelAttribute 方法,提取出来,放到 @ControllerAdvice 中。
2、对 AOP 拦截规则添加注解匹配,例如:
|
1 |
execution( public * com.blog.controller.*.*(..)) && ( @annotation (org.springframework.web.bind.annotation.RequestMapping)) |
|
1 |
&& ( @annotation (org.springframework.web.bind.annotation.RequestMapping |
表明这样只会拦截 RequestMappping 标注的方法。
注意:
如果是一个方法 a() 调用同一个类中的方法 b() ,如果对方法 a() 做拦截的话, AOP 只会拦截到 a() ,而不会拦截到 b() ,因为啊 a() 对b()的调用是通过 this.b() 调用的,而 AOP 正真执行的是生成的代理类,通过 this 自然无法拦截到方法 b() 了。
了解Spring @Around使用及注意
注意:
1、 Spring 切面注解的顺序
@before @Around ( 要代理的方法执行在其中) @AfterReturning @after2、没有 @Around ,则 要代理的方法执行 异常才会被 @AfterThrowing 捕获;
3、在 @Around 如何执行 要代理的方法执行
|
1 2 3 4 5 6 7 8 9 10 11 |
@Around ( "execution(* cn测试数据.xalead.spring.MeInterface.*(..)) || execution(* cn测试数据.xalead.spring.KingInterface.*(..))" ) public Object test(ProceedingJoinPoint proceeding) { Object o = null ; try { //执行 o = proceeding.proceed(proceeding.getArgs()); } catch (Throwable e) { e.printStackTrace(); } return o; } |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
原文链接:https://blog.csdn.net/wxgxgp/article/details/82526311
查看更多关于SpringAop @Around执行两次的原因及解决的详细内容...