Spring之AOP学习

现在学习一下spring之aop

AOP概念

关键字含义
aspect切面,关注点(我可以做哪个方面的事情)。
PointCut切点,定义切面规则(我可以帮哪些人做事情)
Joinpoint连接点,需要代理的具体方法(需要代理的具体的事情)
Target Object被代理的对象(目标对象)
Advice回调的通知 (在什么时间织入什么样的行为)

我们可以思考一下,aop的出现是为了解决什么场景,由于aop的目的是为了解决一类问题,对于这一类来说,我们可以理解为aop是针对于某些类(比如针对于漂泊在外寻找廉价的出租屋亦或是针对于漂泊在外依然心系学业想要考取研究生的这些人)

AOP的代理方式

名称注解使用时机
前置通知@BeforePointCut方法执行前,调用织入方法
后置通知@AfterPointCut方法执行完后调用织入方法
环绕通知@Around在@Before 前执行,在@After前执行
返回通知@AfterReturning目标方法返回前调用(返回参数不为void)
异常通知@AfterThrowing目标方法抛出异常的时候调用

AOP的执行顺序

  1. @Around
  2. @Before
  3. @Around
  4. @After
  5. @AfterReturning
  6. @AfterThrowing

pointCut 表达式匹配规则

规则名称规则说明案例
execution匹配方法签名需要满足execution中描述的方法签名@Pointcut(“execution(public * com.spring.aop.xiaozhe.controller..(…))”)
target匹配目标对象(非代理实例)的类型满足target 中的描述的类型,表达式类型为全限定名,不支持通配符@Before(value = “target(com.spring.aop.xiaozhe.UserService)”)
@target匹配目标对象拥有@target描述中给出的annotation,表达式类型为全限定名,不支持通配符@Before(value = “@target(com.spring.aop.xiaozhe.TestTargetAnnotation)”)
within匹配包或者类型满足within中描述的包或者类型的类的所有非私有方法@Before(value = “within(com.spring.aop.xiaozh.*)”)
@within匹配对象类型拥有@within描述中给出的annotation,功能和@target一样@within 和@target的区别@within:当前类有注解,则对该类对父类重载的方法和自有方法产生效果,其他的方法均无效果。若子类无注解,且子类调用的是该类的方法(即子类未对该方法进行重载),则有效果。@target:若当前类有注解,则对该类继承、自有、重载的方法有效。若子类无注解,则无效果
this匹配目标对象的类型满足this中的描述的类型(可以是父类,接口)@Before(value = “this(com.spring.aop.xiaozhe.Service)”)
args匹配方法的参数满参数类型为args中描述的类型,同时也用于接收目标方法的参数@Before(value = “args(java.lang.String,java.lang.Integer)”)
@args匹配方法参数实际类型包含@args描述中给出的annotation@Before(value = “@args(com.spring.aop.xiaozhe.ArgstAnnotation)”)
@annotation匹配方法上拥有@annotation 描述中给出的注解bean的名字或者为bean描述中的名字或者Id
beanbean的名字或者为bean描述中的名字或者Id@Before(value = “bean(userService)”)

每个代理方法可选参数

JoinPoint
切点信息,可通过JoinPoint获取方法运行时的一些参数,如:目标对象、目标对象的方法参数值 、代理对象等信息,方法明细如下
//获得被代理的方法信息
	//如:String org.springframework.aop.UserService.getUser(String,String)
	String toString();

   //获得被代理的方法信息
	//如:execution(public java.lang.String //org.springframework.aop.UserService.getUser(java.lang.String,java.lang.String))
    String toShortString();

   //获得被代理的方法信息
   //如:execution(UserService.getUser(..))
    String toLongString();

  	//获得AOP代理对象
    Object getThis();

   	//获得被代理对象
    Object getTarget();

  	//获取被代理方法的参数值
    Object[] getArgs();

 	//Signature封装了被代理对象的方法信息
	//getDeclaringType获取被代理对象的类名:class org.springframework.aop.UserService
	//getName 获得方法名:如:getUser
    //获取被代理的方法名,参数名,所属类的Class等信息
    Signature getSignature();

 
    SourceLocation getSourceLocation();

   
    String getKind();
ProceedingJoinPoint
JoinPoint 子接口接口,除了拥有JoinPoint 同样的功能外,还提供了proceed方法可调用目标类的方法,ProceedingJoinPoint只能在环绕通知里使用。 

如果你要在其他通知方法中使用此参数会提示下面错误:

java.lang.IllegalArgumentException: ProceedingJoinPoint is only supported for around advice

测试代码

测试控制类代码
package com.spring.aop.xiaozhe.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @ClassName AopController
 * @Description AOP测试类
 * @Author ZhengZhe
 * @Date 2020/1/14 14:41
 * @Version 1.0
 **/
@Api(tags = "AopController", description = "AOP测试类")
@RestController
@RequestMapping("/aopTest")
public class AopController {
    @ApiOperation("测试AOP代理")
    @RequestMapping(value = "aopTestMethod", method = RequestMethod.POST)
    @ResponseBody
    public Object aopTestMethod(){
        long startTime = System.currentTimeMillis();

        // 1 输出上半部分
        int starLine = 19;
        for (int i = 1; i <= starLine; i++) {
            // 1.1 输出空白部分
            for (int j = 0; j <= starLine - i; j++) {
                System.out.print("A");
            }
            //输出空字符串
            for (int m = 1; m <= 5; m++) {
                System.out.print(" ");
            }
            // 1.2 输出*
            for (int k = 1; k <= 2 * i - 1; k++) {
                System.out.print("*");
            }
            //输出空字符串
            for (int n = 1;n <= 5 ; n++) {
                System.out.print(" ");
            }
            //输出右侧A
            for (int j = 0; j <= starLine - i; j++) {
                System.out.print("B");
            }
            System.out.println();
        }
        // 2 输出下半部分
        for (int i = 1; i <= starLine - 1; i++) {
            // 2.1 输出A
            for (int j = 0; j <= i; j++) {
                System.out.print("A");
            }
            //输出空串
            for (int m= 1; m <= 5 ; m++) {
                System.out.print(" ");
            }
            // 2.2 输出*
            for (int k = 1; k <= (-2 * i + 2 * starLine - 1); k++) {
                System.out.print("*");
            }
            //输出空串
            for (int k= 1; k <= 5; k++) {
                System.out.print(" ");
            }
            for (int j = 0; j <= i; j++) {
                System.out.print("B");
            }
            System.out.println();
        }
        long endTime = System.currentTimeMillis();
        return "执行该方法消耗了 : "+(endTime-startTime)+" ms";
    }
}

AOP切面类
package com.spring.aop.xiaozhe.component;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import com.spring.aop.xiaozhe.dto.WebLog;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName WebLogAspect
 * @Description 日志切面类
 * @Author ZhengZhe
 * @Date 2020/1/14 14:41
 * @Version 1.0
 **/
@Aspect//该注解注明此类是一个切面类
@Component//注入到spring容器中
@Order(1)//执行顺序
public class WebLogAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);
    //定义切点 即 切面规则
    @Pointcut("execution(public * com.spring.aop.xiaozhe.controller.*.*(..))")
    public void webLog() {
    }
    //前置通知
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        System.out.println("此时执行了前置通知");
    }
    //返回通知
    @AfterReturning(value = "webLog()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable {
        System.out.println("此时执行了返回通知");
    }
    //后置通知
    @After(value = "webLog()")
    public void doAfter(JoinPoint joinPoint){
        System.out.println("此时执行了后置通知");
    }
    //异常通知
    @AfterThrowing(value = "webLog()")
    public void doAfterThrowing(JoinPoint joinPoint){
        System.out.println("此时执行了异常通知");
    }

    //环绕通知
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("此时开始执行环绕通知");
        long startTime = System.currentTimeMillis();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录请求信息
        WebLog webLog = new WebLog();
        Object result = joinPoint.proceed();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method.isAnnotationPresent(ApiOperation.class)) {
            ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
            webLog.setDescription(apiOperation.value());
        }
        long endTime = System.currentTimeMillis();
        String urlStr = request.getRequestURL().toString();
        webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
        webLog.setIp(request.getRemoteUser());
        webLog.setMethod(request.getMethod());
        webLog.setParameter(getParameter(method, joinPoint.getArgs()));
        webLog.setResult(result);
        webLog.setSpendTime((int) (endTime - startTime));
        webLog.setStartTime(startTime);
        webLog.setUri(request.getRequestURI());
        webLog.setUrl(request.getRequestURL().toString());
        LOGGER.info("{}", JSONUtil.parse(webLog));
        System.out.println("此时执行环绕通知结束");
        return result;
    }

    /**
     * 根据方法和传入的参数获取请求参数
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }
}

日志包装类
package com.spring.aop.xiaozhe.dto;

/**
 * @ClassName WebLog
 * @Description 日志包装类
 * @Author ZhengZhe
 * @Date 2020/1/14 14:41
 * @Version 1.0
 **/
public class WebLog {
    /**
     * 操作描述
     */
    private String description;

    /**
     * 操作用户
     */
    private String username;

    /**
     * 操作时间
     */
    private Long startTime;

    /**
     * 消耗时间
     */
    private Integer spendTime;

    /**
     * 根路径
     */
    private String basePath;

    /**
     * URI
     */
    private String uri;

    /**
     * URL
     */
    private String url;

    /**
     * 请求类型
     */
    private String method;

    /**
     * IP地址
     */
    private String ip;

    /**
     * 请求参数
     */
    private Object parameter;

    /**
     * 请求返回的结果
     */
    private Object result;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Long getStartTime() {
        return startTime;
    }

    public void setStartTime(Long startTime) {
        this.startTime = startTime;
    }

    public Integer getSpendTime() {
        return spendTime;
    }

    public void setSpendTime(Integer spendTime) {
        this.spendTime = spendTime;
    }

    public String getBasePath() {
        return basePath;
    }

    public void setBasePath(String basePath) {
        this.basePath = basePath;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public Object getParameter() {
        return parameter;
    }

    public void setParameter(Object parameter) {
        this.parameter = parameter;
    }

    public Object getResult() {
        return result;
    }

    public void setResult(Object result) {
        this.result = result;
    }
}

测试代码执行结果

当没有异常出现时
此时开始执行环绕通知
此时执行了前置通知
AAAAAAAAAAAAAAAAAAA     *     BBBBBBBBBBBBBBBBBBB
AAAAAAAAAAAAAAAAAA     ***     BBBBBBBBBBBBBBBBBB
AAAAAAAAAAAAAAAAA     *****     BBBBBBBBBBBBBBBBB
AAAAAAAAAAAAAAAA     *******     BBBBBBBBBBBBBBBB
AAAAAAAAAAAAAAA     *********     BBBBBBBBBBBBBBB
AAAAAAAAAAAAAA     ***********     BBBBBBBBBBBBBB
AAAAAAAAAAAAA     *************     BBBBBBBBBBBBB
AAAAAAAAAAAA     ***************     BBBBBBBBBBBB
AAAAAAAAAAA     *****************     BBBBBBBBBBB
AAAAAAAAAA     *******************     BBBBBBBBBB
AAAAAAAAA     *********************     BBBBBBBBB
AAAAAAAA     ***********************     BBBBBBBB
AAAAAAA     *************************     BBBBBBB
AAAAAA     ***************************     BBBBBB
AAAAA     *****************************     BBBBB
AAAA     *******************************     BBBB
AAA     *********************************     BBB
AA     ***********************************     BB
A     *************************************     B
AA     ***********************************     BB
AAA     *********************************     BBB
AAAA     *******************************     BBBB
AAAAA     *****************************     BBBBB
AAAAAA     ***************************     BBBBBB
AAAAAAA     *************************     BBBBBBB
AAAAAAAA     ***********************     BBBBBBBB
AAAAAAAAA     *********************     BBBBBBBBB
AAAAAAAAAA     *******************     BBBBBBBBBB
AAAAAAAAAAA     *****************     BBBBBBBBBBB
AAAAAAAAAAAA     ***************     BBBBBBBBBBBB
AAAAAAAAAAAAA     *************     BBBBBBBBBBBBB
AAAAAAAAAAAAAA     ***********     BBBBBBBBBBBBBB
AAAAAAAAAAAAAAA     *********     BBBBBBBBBBBBBBB
AAAAAAAAAAAAAAAA     *******     BBBBBBBBBBBBBBBB
AAAAAAAAAAAAAAAAA     *****     BBBBBBBBBBBBBBBBB
AAAAAAAAAAAAAAAAAA     ***     BBBBBBBBBBBBBBBBBB
AAAAAAAAAAAAAAAAAAA     *     BBBBBBBBBBBBBBBBBBB
2020-01-14 15:23:30.715  INFO 6084 --- [nio-8080-exec-2] c.s.aop.xiaozhe.component.WebLogAspect   : {"result":"执行该方法消耗了 : 14 ms","basePath":"http://127.0.0.1:8080","method":"POST","description":"测试AOP代理","startTime":1578986610664,"uri":"/aopTest/aopTestMethod","url":"http://127.0.0.1:8080/aopTest/aopTestMethod","spendTime":21}
此时执行环绕通知结束
此时执行了后置通知
此时执行了返回通知
当执行代码中存在异常时
我们需要在代码中写一个运行时异常,比如 int xiaozhe = 1/0
此时开始执行环绕通知
此时执行了前置通知
此时执行了后置通知
此时执行了异常通知
2020-01-14 15:32:13.222 ERROR 11608 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.ArithmeticException: / by zero] with root cause

java.lang.ArithmeticException: / by zero

总结

通过以上的叙述,我们大概可以了解到AOP的应用场景,比如需要项目使用的日志系统,我们要获取每个方法中的日志信息(主要是为了捕获异常日志),需要定一套符合项目的AOP扫描规则.亦或是应用于缓存,提高用户的访问体验,都可以使用AOP,当然以上的测试代码只是简单的举例,具体应用还需要在实际的项目中考量.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值