SpringBoot之切面AOP

SpringBoot提供了强大AOP支持,我们前面讲解过AOP面向切面,所以这里具体AOP原理就补具体介绍;

 

AOP切面主要是切方法,我们一般搞一些日志分析和事务操作,要用到切面,类似拦截器;

 

@Aspect注解是切面注解类

 

@Pointcut切点定义

 

@Before是方法执行前调用

 

@After是方法执行后调用

 

@AfterReturning方法执行返回值调用

 

Service层本身就可以切入事务,所以我们这类搞个常用的 切controller层方法

每个执行controller层的方法 都记录下请求Url,访问者IP 执行类方法参数等信息;

 

定义一个切面类:RequestAspect

 1 package com.hik;
 2 
 3 import javax.servlet.http.HttpServletRequest;
 4 
 5 import org.apache.log4j.Logger;
 6 import org.aspectj.lang.JoinPoint;
 7 import org.aspectj.lang.annotation.After;
 8 import org.aspectj.lang.annotation.AfterReturning;
 9 import org.aspectj.lang.annotation.Aspect;
10 import org.aspectj.lang.annotation.Before;
11 import org.aspectj.lang.annotation.Pointcut;
12 import org.springframework.stereotype.Component;
13 import org.springframework.web.context.request.RequestContextHolder;
14 import org.springframework.web.context.request.ServletRequestAttributes;
15 
16 @Aspect
17 @Component
18 public class RequestAspect {
19     
20     private Logger log = Logger.getLogger(RequestAspect.class);
21     
22     @Pointcut("execution(public * com.hik.controller.*.*(..))")
23     public void log() {
24         
25     }
26     
27     @Before("log()")
28     public void deoBefore(JoinPoint joinPoint) {
29         log.info("方法执行前...");
30         ServletRequestAttributes sra=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
31         HttpServletRequest request=sra.getRequest();
32         log.info("url:"+request.getRequestURI());
33         log.info("ip:"+request.getRemoteHost());
34         log.info("method:"+request.getMethod());
35         log.info("class_method:"+joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
36         log.info("args:"+joinPoint.getArgs());
37     }
38     
39     @After("log()")
40     public void doAfter(JoinPoint joinPoint){
41         log.info("方法执行后...");
42     }
43      
44     @AfterReturning(returning="result",pointcut="log()")
45     public void doAfterReturning(Object result){
46         log.info("执行返回值:"+result);
47     }
48 
49 }
View Code

execution(public * com.hik.controller.*.*(..)) 这个定义 意思是 对 com.hik.controller包下的任意类,任意方法,任意参数,任意返回值的方法都进行切入

 

我们测试 StudentController

请求:http://localhost/studentAdd.html

点击提交

控制台显示:

 

 

这里得到了我们需要的信息;

 

当然这里用到了日志  springboot推荐logback log4j的升级版 用法基本差不多;

 

posted @ 2018-08-26 20:33  心和梦的方向  阅读(2881)  评论(0编辑  收藏  举报