Spring Boot AOP

作者: 玩命有人疼 | 来源:发表于2018-07-24 10:21 被阅读62次

注:AOP称为面向切面编程,在程序开发中常用来解决一些系统公共的问题,比如日志,事务,权限拦截等等,本文主要讲述Spring AOP的使用,具体原理,在以后的章节进行讲解,Spring AOP原理讲解后,我们详细就观察Spring的核心代码AbstractApplicationContext.refresh()方法。

基本概念

1、Aspect(切面):通常是一个类,里面可以定义切入点和通知,比如Log类。
2、JointPoint(连接点):程序执行过程中明确的点,即在哪个地方进行拦截。
3、Advice(通知):AOP在特定的切入点上执行的增强处理,主要包括以下几种方式:before,after,afterReturning,afterThrowing,around
(1)前置通知(Before):在目标方法前调用。
(2)后置通知(After):在目标方法后调用,无论是否有异常都执行。
(3)环绕通知(Around):将 Before 和 After ,甚至抛出增强和返回增强合到一起,即动态代理功能一样。
(4)返回通知(AfterReturning):在方法返回结果后执行,该增强可以接收到目标方法返回结果,前提没有异常的情况下。
(5)异常通知(AfterThrowing):在目标方法抛出对应的类型后执行,可以接收到对应的异常信息,前提抛出异常的情况下。
4、Pointcut(切入点):就是带有通知的连接点,在程序中主要体现为书写切入点表达式
5、AOP代理:AOP框架创建的对象,代理就是目标对象的加强。

具体实例

该实例功能,在做除法运算时,将其日志打印输出,具体代码如下:

Calc.java 业务类

package com.itbofeng;
import org.springframework.stereotype.Service;
//核心业务逻辑类,保证业务逻辑类的功能单一,使用Spring Aop降低代码的侵入性
@Service
public class Calc {
    //进行触发运算功能
    public int div(int a, int b) {
        return a/b;
    }
}

Log.java 切面类:日志记录

package com.itbofeng;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Arrays;

//切面类:日志记录功能
@Aspect
@Component
public class Log {

    //切点
    @Pointcut("execution(public * com.itbofeng.*.*(..))")
    public void logPointCut(){}

    //前置通知
    @Before("logPointCut()")
    public void calcBefore(JoinPoint joinPoint){
        String name=joinPoint.getSignature().getName();
        Object [] args=joinPoint.getArgs();
        System.out.println("Log.calcBefore exec method "+name+",the args are"+ Arrays.asList(args));
    }
    //返回通知
    @AfterReturning(returning = "ret",pointcut = "logPointCut()")
    public void  calcAfterReturning(JoinPoint joinPoint,Object ret){
        String name=joinPoint.getSignature().getName();
        Object [] args=joinPoint.getArgs();
        System.out.println("Log.AfterReturning exec method "+name+",the args are"+ Arrays.asList(args)+",the result is "+ret);
    }

    //异常通知
    @AfterThrowing(pointcut="logPointCut()",throwing="e")
    public void  calcAfterThrowing(JoinPoint joinPoint,Exception e){
        String name=joinPoint.getSignature().getName();
        Object [] args=joinPoint.getArgs();
        System.out.println("Log.AfterThrowing exec method "+name+",the args are"+ Arrays.asList(args)+",the Exception is "+e.getMessage());
    }
    //后置通知
    @After("logPointCut()")
    public void calcAfter(JoinPoint joinPoint){
        String name=joinPoint.getSignature().getName();
        Object [] args=joinPoint.getArgs();
        System.out.println("Log.calcAfter exec method "+name+",the args are"+ Arrays.asList(args)+"....");
    }


    @Around("logPointCut()")
    public Object calcAround(ProceedingJoinPoint proceedingJoinPoint){
        //相当于前置通知
        Object [] args=proceedingJoinPoint.getArgs();//参数
        System.out.println("Log.calcAround before...,the args are"+Arrays.asList(args));
        Object ret=null;
        try {
            ret=proceedingJoinPoint.proceed();//返回值
            //相当于返回通知
            System.out.println("Log.calcAround AfterReturning...,the result is "+ret);
        } catch (Throwable e) {
            //相当于异常通知
            System.out.println("Log.calcAround AfterThrowing..."+e.getMessage());
            e.printStackTrace();
        }finally {
            //相当于后置通知
            System.out.println("Log.calcAround after...");
            return ret;
        }
    }
}

MainConfig.java 配置类

package com.itbofeng;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan
//开启AspectJ自动代理功能相当于xml中的<aop:aspectj-autoproxy />
@EnableAspectJAutoProxy
//配置类:这里使用的是基于注解的方式,相当于xml方式的配置文件
public class MainConfig {

}

AopApplicationTests.java 测试类

package com.itbofeng;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
//测试类
public class AopApplicationTests {
    @Test
    public void testAop() throws Exception {
        ApplicationContext applicationContext=new AnnotationConfigApplicationContext(MainConfig.class);
        Calc calc=applicationContext.getBean(Calc.class);
        calc.div(1,1);//改变这里为1/0可以测试异常情况下
    }
}

运行结果:

运行1:前提说明:先注释环绕通知,运行calc.div(1,1);正常情况下:

Log.calcBefore exec method div,the args are[1, 1]
Log.calcAfter exec method div,the args are[1, 1]....
Log.AfterReturning exec method div,the args are[1, 1],the result is 1

Process finished with exit code 0

运行2:前提说明:先注释环绕通知,运行calc.div(1,0);异常情况下:

Log.calcBefore exec method div,the args are[1, 0]
Log.calcAfter exec method div,the args are[1, 0]....
Log.AfterThrowing exec method div,the args are[1, 0],the Exception is / by zero

java.lang.ArithmeticException: / by zero

运行3:前提说明:先注释除环绕外的其他通知,运行calc.div(1,1);正常情况下:

Log.calcAround before...,the args are[1, 1]
Log.calcAround AfterReturning...,the result is 1
Log.calcAround after...

Process finished with exit code 0

运行3:前提说明:先注释除环绕外的其他通知,运行calc.div(1,0);异常情况下:

Log.calcAround before...,the args are[1, 0]
Log.calcAround AfterThrowing.../ by zero
Log.calcAround after...
java.lang.ArithmeticException: / by zero

小结:
本文主要讲解了AOP中的基本概念,以及简单的使用Spring AOP,主要是为了体验一下什么是AOP,在本文中需要掌握以下三个方面:

1、AOP的理解:面向切面编程,是一种编程思想,就像面向对象编程一样,Spring AOP只是一个具体的实现,就像Java是面向对象语言一样。

2、Spring AOP在应用程序中应用场景:在应用程序中AOP主要承担一些系统级别的功能也即一些通用的功能,如日志记录,权限校验,错误处理,事务控制等。

3、注解的使用:需要掌握理解这些注解的使用,以及每个通知方法执行时机。

最后:我这里有Spring、Spring Boot相关的视频教程(由于各种原因,不方便在此公开,还请见谅,不过这视频是我见到我认为最好的教程,不过教程也建议有过Spring使用经验的朋友观看,这样效果会更加好,有好多地方会涉及原理讲解,没有使用过的话,压力会有点大),我就是一边没事的时候看看教程,加上自己的理解,写文章的,所以文章有误的地方,还请大家指正,我一定会虚心学习的,有需要视频教程的朋友,可以私信我如果大家觉得文章不错,点个赞,关注一下,感谢你的支持。

相关文章

网友评论

    本文标题:Spring Boot AOP

    本文链接:https://www.haomeiwen.com/subject/fpvppftx.html