springboot 实现 aop

  1. pom.xml 导入 springboot aop 依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  1. 创建 aspect,在 execution 参数中写上被切的类
@Aspect
@Component
public class IndexAspect {
    private static final Logger logger = LoggerFactory.getLogger(IndexAspect.class);
<span class="hljs-comment">// 公用的切点,该类下所有方法</span>
<span class="hljs-meta">@Pointcut</span>(<span class="hljs-string">"execution(public * com.example.IndexController.*(..))"</span>)
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">log</span><span class="hljs-params">()</span> </span>{
    logger.info(<span class="hljs-string">"调用 log() "</span>);
}

<span class="hljs-comment">// 使用log函数定义的 execution,不执行log()方法</span>
<span class="hljs-meta">@Before</span>(<span class="hljs-string">"log()"</span>)
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doBefore</span><span class="hljs-params">(JoinPoint joinPoint)</span> </span>{
    logger.info(<span class="hljs-string">"调用 doBefore"</span>);
    ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
    logger.info(<span class="hljs-string">"获取 request"</span>);
    HttpServletRequest request = attributes.getRequest();
    logger.info(<span class="hljs-string">"获取 reponse"</span>);
    attributes.getResponse();
    logger.info(<span class="hljs-string">"获取 session"</span>);
    attributes.getRequest().getSession();
    logger.info(<span class="hljs-string">"获取 class:"</span> + joinPoint.getSignature().getDeclaringTypeName().toString());
    logger.info(<span class="hljs-string">"获取 args:"</span> + joinPoint.getArgs());
}

<span class="hljs-comment">// 获取返回值</span>
<span class="hljs-meta">@AfterReturning</span>(pointcut = <span class="hljs-string">"log()"</span>, returning = <span class="hljs-string">"object"</span>)
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doAfterReturning</span><span class="hljs-params">(Object object)</span> </span>{
    logger.info(<span class="hljs-string">"获取返回值"</span> + object.toString());
}

}

  1. 启动项目,查看控制台日志
com.example.IndexAspect: 调用 doBefore
com.example.IndexAspect: 获取 request
com.example.IndexAspect: 获取 reponse
com.example.IndexAspect: 获取 session
com.example.IndexAspect: 获取 class:com.example.thymeleaf.IndexController
com.example.IndexAspect: 获取 args:
com.example.IndexAspect: index

参考:http://www.fengyunxiao.cn

      </div>
posted @ 2019-06-25 10:47  星朝  阅读(272)  评论(0编辑  收藏  举报