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

问题描述 投票:1回答:1

我对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");
        }
    }
  • 我们可以使用@Before(“ @ annotation(Loggable)”)直接创建两个方法,而无需使用空方法及其名称。似乎实现了相同的操作(它也在控制台中显示了文本数据):
    @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");
        }   
    }

[请您解释一下何时必须使用第二项操作?人们说它允许某些东西,但我不知道这是什么。

java spring spring-aop aspect
1个回答
0
投票

首先,您需要了解切入点和建议的基础。

第二,这些基于注释的配置只是配置方面的一种方式。因此,不要将其视为“带有切入点注释的空方法”,而是将其视为使用注释定义切入点的语法。

回到您的问题。

他们两个都只是在定义一些事前建议。第二种方法是将切入点定义直接放入建议定义中,而第一种方法是为切入点命名,并在建议中引用它。

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

但是,通常有意义的是给切入点起一个有意义的名字,并通过参考您的建议来使用它。它为切入点赋予了具体的含义,并使其将来更易于修改。

© www.soinside.com 2019 - 2024. All rights reserved.