使用 Java Config 配置实现 Spring AOP 注解式与方法规则拦截式

传统的 Spring AOP,我们都是在 spring.xml 中配置切面、切点、通知建言等,今天我们改用 Java Config 配置类的方式来实现AOP的两种拦截方式。

需求:现在我们要定义一个日志工具,该日志工具采用面向切面的编程思想实现,对于我们的编写的业务Service方法,我们要能够在该方法的执行前后,分别加上要做的日志记录。

我们将采用方法规则式拦截注解式拦截两种方式分别演示。

一、方法规则式拦截

(1) 首先创建我们的业务方法

@Service
public class MethodService {
    public void add() {
        System.out.println("执行 add() ...");
    }

    public void say() {
        System.out.println("执行了 say()...");
    }
}

(2)接着定义日志处理切面,这个切面就是我们的日志工具要做的内容

@Aspect
@Component
public class MethodLogAspect {
    /**
     * 声明建言,使用了 execution表达式指定的拦截规则
     */
    @Before("execution(* com.uzipi.aop.execution.service.*.*(..))")
    public void before(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // 日志工具前置处理
        System.out.println("方法规则式拦截,即将执行:" + method.getName());
    }

    /**
     * 声明建言,使用 execution表达式指定的拦截规则,后继处理
     */
    @After("execution(* com.uzipi.aop.execution.service.*.*(..))")
    public void after(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // 日志工具后继处理
        System.out.println("方法规则式拦截,刚刚执行完:" + method.getName());
    }
}

(3)然后定义config配置类,扫描包,并启用AspectJ相关的注解支持

/**
 * MethodAopConfig: 方法规则式拦截 AOP配置类,相当于 spring-aop.xml
 */
@Configuration
@ComponentScan("com.uzipi.aop.execution")
@EnableAspectJAutoProxy  // @EnableAspectJAutoProxy开启了Spring对AspectJ的支持
public class MethodAopConfig {

}

(4)最后是 main() 入口

public class ExecutionAopMain {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = 
              new AnnotationConfigApplicationContext(MethodAopConfig.class);
        MethodService methodService = ctx.getBean(MethodService.class);
        // 调用服务,触发切面
        methodService.add();
        methodService.say();
        // 关闭上下文
        ctx.close();
    }
}

输出结果:

方法规则式拦截,即将执行:add
执行 add() ...
方法规则式拦截,刚刚执行完:add
方法规则式拦截,即将执行:say
执行了 say()...
方法规则式拦截,刚刚执行完:say

从输出结果上我们就可以发现,只要我们调用了业务方法,匹配方法规则的都会自动的加上AOP的前置后后置处理。从粒度上来看要粗放一些,如果需要精确匹配执行AOP的方法,需要编写较复杂的 execution 表达式。

下面我们换一种方式,采用注解式拦截。

二、注解式拦截

(1)第一步是创建自定义注解,用于描述我们的拦截动作的元数据

/**
 * Action: 定义拦截规则的注解
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Action {
    // 拦截规则的名称
    String name();
}

(2)在业务方法上加上自定义注解@Action,将这个方法声明为切点

@Service
public class AnnotationService {

    @Action(name = "通过注解拦截")
    public void add() {
        System.out.println("执行了 add()...");
    }

    // say() 方法没有加 @Action 注解,因此拦截不会对 say() 生效
    public void say() {
        System.out.println("执行了 say()...");
    }
}

(3)定义切面

/**
 * AnnotationLogAspect: 注解式日志切面
 */
@Aspect
@Component
public class AnnotationLogAspect {
    /**
     * 声明切点,使用了注解 @Action 的方法会拦截生效
     */
    @Pointcut("@annotation(com.uzipi.aop.annotation.annotation.Action)")
    public void annotationPointcut() {
    }

    /**
     * 声明前置建言,复用了@Pointcut注解定义的切点
     */
    @Before("annotationPointcut()")
    public void before(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Action action = method.getAnnotation(Action.class); //获取方法上定义的注解,粒度更细更精确
        System.out.println("注解式拦截,即将执行:" + action.name()); // 反射获得注解上的属性,然后做日志相关的记录操作
    }

    /**
     * 声明后继建言,复用了@Pointcut注解定义的切点
     */
    @After("annotationPointcut()")
    public void after(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Action action = method.getAnnotation(Action.class);
        System.out.println("注解式拦截,刚刚执行完:" + action.name());
    }
}

(4)接着创建config配置类,相当于 spring-aop.xml

/**
 * AnnotationAopConfig: 注解式拦截 AOP配置类,相当于 spring-aop.xml
 */
@Configuration
@ComponentScan("com.uzipi.aop.annotation")
@EnableAspectJAutoProxy  // @EnableAspectJAutoProxy开启了Spring对AspectJ的支持
public class AnnotationAopConfig {

}

(5)最后是 main() 入口

public class AnnotationAopMain {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = 
            new AnnotationConfigApplicationContext(AnnotationAopConfig.class);
        AnnotationService annotationService = ctx.getBean(AnnotationService.class);
        // 调用服务,触发切面
        annotationService.add();
        annotationService.say();
        // 关闭上下文
        ctx.close();
    }
}

输出结果:

注解式拦截,即将执行:通过注解拦截 add()
执行了 add()...
注解式拦截,刚刚执行完:通过注解拦截 add()
执行了 say()...

通过输出结果,可以看到add()被AOP拦截处理了,而say()没有,产生区别的原因就是我在add()方法上加了@Action注解,say()方法上没有加注解。

总结

  1. 相较于传统的 xml 配置文件,使用 Java Config 注解方式可以更简单的实现无 xml 文件的配置
  2. AOP的两种拦截方式在使用了Java Config进行配置的基础上,也会有各自的优缺点。
方法规则式拦截

优点

  • 方法规则式侵入性低,在分工开发的环境中个,编写业务方法代码的人并不需要知道他编写的业务方法的AOP处理逻辑,只要按照统一的命名规则对方法命名即可,然后由编写AOP的人根据统一的方法命名来选择对哪些方法实施拦截。

  • 适用于业务代码开发时不考虑AOP处理,业务代码开发完成后再开发AOP的,可以实现无缝接入。

缺点

  • 方法规则式灵活性稍差一点,在设计切面时,如果要实现精确的方法拦截处理或者对不同的方法实现不同的处理,execution表达式会写的比较多。
注解式拦截

优点

  • 注解式AOP灵活性高,只要定义好注解,想对哪个业务方法做拦截,只需要加上注解就可以了,A方法用A注解,B方法用B注解,不同的业务逻辑使用不同的拦截处理逻辑,这些工作只需要在切面中声明即可。

缺点

  • 正因为较高的侵入性,需要在业务代码中加上AOP注解,需要在设计阶段就考虑清楚AOP的拦截逻辑。

你可能感兴趣的:(使用 Java Config 配置实现 Spring AOP 注解式与方法规则拦截式)