Search code examples
javastringspringaoppointcut

Pointcut annotation vs Final String


So I'm studying tutorial on Spring AOP and when the concept of pointcut annotations was explained I thought "why not use final private String?". I've looked up but didn't find anything that might explain why use the overhead of pointcut?

with pointcut:

@Before("pointcutMethod()")
public void loggingAdvice(){
    System.out.println("loggin advice");
}

@Before("pointcutMethod()")
public void loggingAdviceTwo(){
    System.out.println("loggin advice2");
}

@Before("pointcutMethod() || secondPointcutMethod()")
public void loggingAdviceTree(){
    System.out.println("loggin advice3");
}

@Pointcut("execution(public * get*())")
public void pointcutMethod(){}

 @Pointcut("within(shapes.Circle)")
public void secondPointcutMethod(){}

and with private final String:

private static final String EXECUTION_PUBLIC_GET = "execution(public * get*())";
private static final String WITHIN_SHAPES_CIRCLE = "within(shapes.Circle)";
private static final String OR = " || ";

@Before(EXECUTION_PUBLIC_GET)
public void loggingAdvice(){
    System.out.println("loggin advice");
}


@Before(EXECUTION_PUBLIC_GET)
public void loggingAdviceTwo(){
    System.out.println("loggin advice2");
}

@Before(EXECUTION_PUBLIC_GET + OR + WITHIN_SHAPES_CIRCLE)
public void loggingAdviceTree(){
    System.out.println("loggin advice3");

edit: I was pointed at fact that there is xml-based configuration with AOP, so I edited the question to address only annotation of pointcut.


Solution

  • The usage of pointcuts add a level of abstraction/redirection between the advice and the actual join points, improving scalability and separation of concerns:

    • In case of refactoring of your program, only the pointcuts need to be adapted, not every advices.
    • Pointcuts and advices can be defined separately (for example, the maintainer of a library can provide some pointcuts to the actual user of the library).
    • Composition (combination) of pointcuts allows to keep things clear (in your example, you could have defined a @Pointcut("pointcutMethod() || secondPointcutMethod()") ).

    More details and examples can be found directly in the spring documentation: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-pointcuts

    But as said by Boris Pavlović, it is a matter of style, and you should use what is the most convenient to you.