Spring 使用方法而不是 @annotation 的 AOP 建议:为什么?

Spring AOP advice with method rather than @annotation : Why?

我对 Spring 的建议一窍不通。有两种方法可用于创建具有两个建议的方面:

    @Component
    @Aspect
    public class TestAppli{

        private static final Logger LOGGER = LoggerFactory.getLogger(TestAppli.class);

        @Pointcut("@annotation(Loggable)")
        public void executeLogging(){
        }

        @Before("executeLogging()")
        public void method1(JoinPoint joinPoint){
            LOGGER.info("method 1 is called");
        }

        @Before("executeLogging()")
        public void method2(JoinPoint joinPoint){
            LOGGER.info("method 2 is called");
        }
    }
    @Component
    @Aspect
    public class TestAppli {

        private static final Logger LOGGER = LoggerFactory.getLogger(TestAppli.class);

        @Before("@annotation(Loggable)") 
        public void method1(JoinPoint joinPoint){
            LOGGER.info("method 1 iscalled");
        }

        @Before("@annotation(Loggable)") 
        public void method2(JoinPoint joinPoint){
            LOGGER.info("method 2 is called");
        }   
    }

请你解释一下什么时候必须使用第二个操作?人们说它允许某些东西,但我不明白那东西是什么。

首先你需要了解什么是切入点和通知的基础知识。

其次,这些基于注解的配置只是配置Aspects的一种方式。所以不要将其视为"empty method with a pointcut annotation",而是将其视为使用注释定义切入点的语法。

回到你的问题。

他们都只是定义了一些Before-advices。在第二种方式中,您将切入点定义直接放入建议定义中,而在第一种方式中,您为切入点命名,并在建议中引用它。

没有对错之分,只要你知道自己在做什么。例如,对于非常简单直接的切入点,仅在一两个通知中使用,您可以像第二种方式一样将其直接放在通知中。

但是,通常为您的切入点起一个有意义的名称并通过在您的建议中引用来使用它通常是有意义的。它为您的切入点赋予语义意义,并​​使其在将来更容易修改。

SpringAOP的基本概念可以阅读here

Advice: Action taken by an aspect at a particular join point

Pointcut: A predicate that matches join points.

使用 @PointCut 注释方法,声明了一个切入点表达式以匹配连接点。

此方法名称随后可用于将切入点表达式与 Advice.

相关联

当直接用 advice 编写切入点表达式时,它被称为就地切入点表达式。

据我所知,使用就地切入点表达式时没有区别。同时使用 @PointCut 注释方法的好处是我们可以 combine 几种不同的这样的方法来获得更具可读性的 Advice。

希望对您有所帮助