Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding in-place pointcut expression in Spring AOP

Tags:

java

spring

aop

I'm using Spring AOP. I'm giving my pointcuts like:

@Pointcut("execution(* com.demo.Serviceable+.*(..))")
public void serviceMethodCalls() {
}

Is it possible to avoid the in-place pointcut expression in Spring AOP?

like image 825
Veera Avatar asked Dec 22 '22 11:12

Veera


2 Answers

It depends on what style of AOP you choose with Spring. As you stick with the annotation based approach, there is not much you can get except having constants for the expressions located in an extenal class.

This is due to the @Aspect annotation based AOP style dedicated to colocate where and what. You can somehow get some configurability by using abstract method and binding the pointcut to it.

@Aspect
public abstract class MyAspect {

  protected abstract pointcut();


  @Before("pointcut()")
  public void myAdviceMethod() {
    // Advice code goes here
  }
}


public class ConcreteAspect extends MyAspect {

  @Pointcut("execution(* com.acme.*.*(..))")
  protected pointcut() {
  )
}

This is possible but seems rather awkward to me as the implementor has to know that @Pointcut is required on the method. If she forgets to place it, it will crash entirely.

If you need the flexibility to have advice and pointcut separated you better stick to the XML based configuration (see Spring documentation for example).

A kind of man in the middle is the possibility to tie your pointcut to a custom annotation and let the users decide where to place it and thus, when to get your advice applied. Spring documentation (chapter 6.2.3.4) gives more info on that.

Regards, Ollie

like image 165
Oliver Drotbohm Avatar answered Jan 03 '23 13:01

Oliver Drotbohm


Here's how you could define a configurable Spring AOP Advice with Java Config:

@Configuration
public class ConfigurableAdvisorConfig {

    @Value("${pointcut.property}")
    private String pointcut;

    @Bean
    public AspectJExpressionPointcutAdvisor configurabledvisor() {
        AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor();
        advisor.setExpression(pointcut);
        advisor.setAdvice(new MyAdvice());
        return advisor;
    }
}

class MyAdvice implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.println("Before method");
        Object result = invocation.proceed();
        System.out.println("After method");
        return result;
    }
}

pointcut.property can then be defined in your application.properties file

like image 45
got_bainne Avatar answered Jan 03 '23 12:01

got_bainne