【Spring AOP】Spring AOP之如何通过注解的方式实现各种通知类型的AOP操作入门篇(2)

一、使用Java配置启用@AspectJ支持

1)引入AOP Maven坐标

  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>5.2.1.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.4</version>
      <scope>compile</scope>
    </dependency>

2)使用@EnableAspectJAutoProxy开启@AspectJ支持

@Configuration
@EnableAspectJAutoProxy
public class AppConfig {

}

二、声明Aspect类

使用@Aspect声明Aspect类

@Aspect
@Component
public class MyAspect {
}

1)Before advice

@Before("execution(* com.zbq.springbootdemo.service.MyService.*(..))")
    public void before() {
        log.info("before ");
    }

2)After(final)advice

@After("execution(* com.zbq.springbootdemo.service.MyService.*(..))")
    public void after() {
        log.info("after ");
    }

3)After return advice

@AfterReturning(pointcut = "execution(* com.zbq.springbootdemo.service.MyService.*(..))",
            returning = "retVal")
    public void afterReturning(String retVal) {
        log.info("AfterReturning ");
        // retVal为被拦截方法的返回结果
        log.info("retVal=" + retVal);
    }

4)After throwing advice

    @AfterThrowing(value = "execution(* com.zbq.springbootdemo.service.MyService.*(..))",
    throwing = "ex")
    public void afterThrowing(Throwable ex) {
        log.info("afterThrowing ");
        log.error("error:"+ex.getMessage());
    }

5)Around advice

@Around(value = "execution(* com.zbq.springbootdemo.service.MyService.*(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("around: before proceed");
        // 执行下一个通知或被拦截的方法,proceedResult为被拦截方法返回结果
        Object proceedResult = joinPoint.proceed();
        log.info("around: proceedResult="+proceedResult);
        // 代理对象
        Object proxyObject = joinPoint.getThis();
        log.info("around: proxyObject="+proxyObject);
        // 被代理对象
        Object target = joinPoint.getTarget();
        log.info("around: target="+target);
        // 方法请求参数
        Object[] args = joinPoint.getArgs();
        log.info("around: args="+args);
        // 方法签名
        Signature signature = joinPoint.getSignature();
        log.info("around: signature="+signature);
        log.info("around: after proceed");
        return proceedResult;
    }
原文地址:https://www.cnblogs.com/756623607-zhang/p/11874048.html