Search code examples
javaspringspring-aopaspect

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


I don't understand one thing with the Spring advices. There are two ways which can be used to create an aspect with two advices:

  • We can create an empty method with a pointcut annotation. Then, we just have to create methods with an advice which contains the empty method name:
    @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");
        }
    }
  • We can directly create the two methods with @Before("@annotation(Loggable)") without using an empty method and its name. It seems to realise the same operations (it shows text data into the console too):
    @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");
        }   
    }

Please, can you explain me when the second operation must be used? People say it permits something but I don't understand what the thing is.


Solution

  • The basic concepts of Spring AOP can be read here

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

    Pointcut: A predicate that matches join points.

    With @PointCut annotated method , a pointcut expression to match a join point is declared.

    This method name can be then used to associate the pointcut expression with an Advice.

    When the pointcut expression is written directly with an advice , it is known as an in-place pointcut expression.

    As far as I know , there are no differences when in-place pointcut expressions are used. At the same time the advantage of using @PointCut annotated method is that we can combine several different such methods to have a more readable Advice.

    Hope this helps