SpringBoot实现AOP

第一步:先导AOP相关的包

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

第二步:定义一个切面类

类加上@Aspect注解,告诉spring boot它是一个切面类
@Component
@Aspect
public class AspectDemo {

    @Pointcut("execution(String com.killer.demo.service.*.*(..)))")
    public void mx(){}

    @Before("mx()")
    public void before(){
        System.out.println("前置通知***");
    }
    @Around("execution(* com.killer.demo.service.*.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕通知之前***");
        Object proceed = joinPoint.proceed();
        System.out.println("环绕通知之后***");
        return proceed;
    }
    @AfterReturning(value = "execution(* com.killer.demo.service.*.*(..))",returning = "obj")
    public void afterReturn(Object obj){
        System.out.println("后置通知***"+obj);
    }
    @AfterThrowing(value = "execution(* com.killer.demo.service.*.*(..))",throwing = "e")
    public void ex(Throwable e){
        System.out.println("异常通知***"+e);
    }
    @After("execution(* com.killer.demo.service.*.*(..))")
    public void after(){
        System.out.println("最终通知***");
    }
}

第三步:在切面类中定义通知方法

切入点表达式说明:@Around("execution(* com.killer.demo.service.*.*(..))") 第一个“*”表示返回参数不限,第二个“*”表示所有子类,第三个“*”表示所有子类的所有方法,“..”表示方法的参数列表不限,可以使用@Pointcut注解统一定义切入点表达式,不用一个一个写表达式了

环绕通知说明:环绕通知的方法需要接收一个对象ProceedingJoinPoint,调用该对象的proceed()用来放行执行方法,否则执行方法结果不会返回。

后置通知说明:后置通知可以接收返回的对象,在切入点表达式上配置returning,然后在方法上接收returning的形参即可

异常通知说明:异常通知可以接收返回的异常对象,在切入点表达式上配置throwing,然后在方法上接收throwing的形参,原理同后置通知接收对象一样,另外,如果程序有异常,程序将直接走异常通知和最终通知了,不会再走环绕后和后置通知了,这块需要注意。

猜你喜欢

转载自blog.csdn.net/guliudeng/article/details/127136058