spring boot整合aop

通知简介

通知的类型共有5个:

@Before:执行前
@After:final增强,类似于final的效果
@AfterThrowing:抛出异常后
@AfterReturning:方法正常返回后
@Around:方法执行前后,可以据此重复执行方法

入门示例

maven 依赖



    org.springframework.boot
    spring-boot-starter-aop

aop类示例


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * Created by r.x on 2019/10/19.
 */
@Aspect
@Slf4j
@Component
public class DemoAspect {

    @Pointcut("execution(public * com.yrx.datasourcemanager.manager.api..*.*(..))")
    private void pointcut() {

    }

    @Before("pointcut()")
    private void beforeExeApi(JoinPoint joinPoint) {
        log.info("Before");
    }

    @After("pointcut()")
    private void afterExeApi(JoinPoint joinPoint) {
        log.info("After");
    }

    @AfterThrowing("pointcut()")
    private void afterThrowingExeApi(JoinPoint joinPoint) {
        log.info("AfterThrowing");
    }

    @AfterReturning("pointcut()")
    private void afterReturningExeApi(JoinPoint joinPoint) {
        log.info("AfterReturning");
    }

    @Around("pointcut()")
    private Object aroundExeApi(ProceedingJoinPoint joinPoint) {
        log.info("Around");
        Object result = null;
        try {
            result = joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return result;
    }
}

注意:必备的注解包括两个:@Aspect和@Component

切点表达式

execution切点表达式,其实就是方法签名

execution(public * com.yrx.datasourcemanager.manager.api..*.*(..))

上述切点表达式解释:
com.yrx.datasourcemanager.manager.api..:表示api包及其子包下的所有类
.
:表示所有方法名
(..):表示不区分方法参数,即所有方法

你可能感兴趣的:(spring boot整合aop)