Springboot整合AOP

AOP:Spring得核心之一,面向切面编程,底层是通过动态代理实现得。实现方式有两种:(1)基本JDK原生动态代理,被代理得类需要实现接口。  (2)基于CGLIB,类和接口都可以代理。

在没有使用boot框架时,使用ssm时,我们需要在配置文件中加上以下配置。    (1)配置切入点。 (2)编写切面类。  (3)将配置类与切入点结合。

          

 现在进入主题,看看boot是如何整合AOP得(boot是2.1.9版本)。

(1)引入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

(2)配置yml

spring:
  aop:
    #采用CGLIB作为作为动态代理,默认true  为了解决使用 JDK 动态代理可能导致的类型转化异常而默认使用 CGLIB (boot1.x版本默认是false)
    proxy-target-class: true
    #是否开启aop自动配置,默认为true
    #意味着自动加上 @EnableAspectAutoProxy 注解
    #该注解用于开启AOP相关注解得支持
    auto: true

(3)编写业务方法

 (4)编写切面类

/**
 * @ClassName
 * @Description
 *
 * @Autor wcy
 * @Date 2020/11/6 13:31
 */
//用于定义一个切面类,切面类上面需要加上@Component才可以生效
@Aspect
@Component
public class AspectController {

   private static final Logger log = LoggerFactory.getLogger(WebController.class);

    /**
     * Pointcut定义切入点,一般为方法级别,通过表达式提现。  匹配springbootaop.demo.controller下面所有得公用方法
     */
    @Pointcut("execution(public * com.example.demo.controller..*.*(..))")
    public void aspect(){};

    /**
     *  @Around("aspect()") 这种定义切入点方式和直接在@Around里面声明具体得切入点表达式一样
     * 环绕通知,更灵活得自定义增强通知,可以注入ProceedingJoinPoint获取相关信息和执行方法
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("aspect()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object object = null;
        log.info("环绕通知开始");
        object =  joinPoint.proceed();
        log.info("环绕通知结束");
        return object;
    }

    /**
     *用于在切入点的流程执行前生效,可以在方法中注入JoinPoint用于获取相关信息
     * @param joinPoint
     */
    @Before("aspect()")
    public void before(JoinPoint joinPoint){
       log.info("我是前置通知");
    }

    /**
     * finally通知,这就意味着无论如何都会执行这个通知(不论是否发生异常),可以在方法中注入JoinPoint用于获取相关信息
     * @param joinPoint
     */
    @After("aspect()")
    public void after(JoinPoint joinPoint){
        log.info("我是finally通知");
    }

    /**
     * 异常通知,出现异常时执行,可以在方法中注入JoinPoint和Throwable用于获取相关信息
     */
    @AfterThrowing("aspect()")
    public void throwing(){
        log.info("我是异常通知");
    }

    /**
     * 后置返回前通知 ,在finally通知之后,方法正常退出前执行,可以注入JoinPoint 和Object 获取相关信息和方法执行成功的返回结果
     * @param object
     */
    @AfterReturning(pointcut = "aspect()",returning = "object")
    public void returning(Object object){
        log.info("我是后置通知,响应结果为:"+object);
    }

}

(5)进入测试,界面输入http://localhost:8080/test1,控制台输入如下

从结果中我们可以看到,当所有通知都存在时,执行顺序如下:

 

 至此boot整合aop也就结束了,此外不同版本得boot,执行顺序也是不一样得,我之前也试了2.3.5得版本,执行得顺序是不同得,这里我就不做说明了,下图便是2.3.5版本得执行顺序。

原文地址:https://www.cnblogs.com/wei-cy/p/13946984.html