Search code examples
spring-bootintellij-ideaaspectj

Conditional Pointcut expression


I want to enable/disable an aspect based on some property from my database. How can I do that?

Also I am using AspectJ LTW, but when I tried using if() in @Pointcut it shows a warning but code compiles fine. I don't want to go that way. Also, I don't want to make my Aspect a component and use Conditional property because then I would have to pick the property from property file. This is a rough snippet of my code.

@Aspect
class A {
  boolean flag = //get value from DB; 
    
  @Pointcut(value = "execution(* com.sample..check(..)) && if())
  public boolean conditional() {
    return flag==true ? true : false;
  }
    
  @Before("conditional()")
  public void doSomething() {
    System.out.println("Hello");
  }
}

aop.xml

<aspectj>
  <aspects>
    <aspect name = "com.sample.aspect.A"/>
    <weaver>
      <include within = "com.sample..*"/>
    </weaver>
  </aspects>
</aspectj>

Solution

  • The error message if pointcut designator isn't supported by Spring in IntelliJ IDEA tells you the truth for Spring AOP aspects. It kicks in automatically if you use an aspect in a Spring project.

    In your case the aspect is a native AspectJ aspect though, not a Spring AOP aspect. IDEA does not understand that, so the solution for your problem is not to change your approach but to just ignore the error message in the editor because what you are doing with if() is correct.

    Alternatively, you can also tell IDEA to suppress Spring AOP error inspection for a method or a whole class:

    For example, after you select "Suppress for class", the error will go away and you will see the annotation @SuppressWarnings("SpringAopErrorsInspection") on top of your class. That should give you some peace of mind. Please note, however, that this will also potentially suppress other Spring AOP syntax errors which would apply to AspectJ too, because Spring AOP pointcut syntax is basically a subset of AspectJ syntax.