SpringAop @Around执行两次的原因以及解决方法

这篇文章主要讲解了“SpringAop @Around执行两次的原因以及解决方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“SpringAop @Around执行两次的原因以及解决方法”吧!

在使用AOP环绕通知做日志处理的时候,发现@Around方法执行了两次,虽然这里环绕通知本来就会执行两次,但是正常情况下是在切点方法前执行一次,切点方法后执行一次,但是实际情况却是,切点方法前执行两次,切点方法后执行两次。

文字不好理解,还是写一下代码:

@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

@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拦截规则添加注解匹配,例如:

execution(public * com.blog.controller.*.*(..)) && (@annotation(org.springframework.web.bind.annotation.RequestMapping))
&& (@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

  • @after

2、没有@Around,则 要代理的方法执行 异常才会被@AfterThrowing捕获;

3、在@Around如何执行 要代理的方法执行

@Around("execution(* cn.com.xalead.spring.MeInterface.*(..)) || execution(* cn.com.xalead.spring.KingInterface.*(..))")
public Object test(ProceedingJoinPoint proceeding) {
    Object o = null;
    try {
        //执行
        o = proceeding.proceed(proceeding.getArgs());
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return o;
}

感谢各位的阅读,以上就是“SpringAop @Around执行两次的原因以及解决方法”的内容了,经过本文的学习后,相信大家对SpringAop @Around执行两次的原因以及解决方法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!