Salman Kazmi Salman Kazmi - 1 month ago 14
Java Question

How to stop method execution in Spring AOP

I have created a bean named BaseCron that has a method

executeBefore()
that is configured in the below configuration of spring to intercept all method calls of the Crons class and execute before them.

The
executeBefore()
method has some validations. I was earlier validating certain conditions and if they were false, I was throwing an exception. This throwing of exception caused the method to fail and hence the methods in the Crons class did not execute.

It is working fine.

Can you suggest some other way in which I can stop the execution of the Crons class without throwing an exception. I tried return but it did not work.

<bean id="baseCronBean" class="com.myapp.cron.Jkl">
</bean>
<aop:config>
<aop:aspect id="cron" ref="baseCronBean">
<aop:pointcut id="runBefore" expression="execution(* com.myapp.cron.Abc.*.*(..)) " />
<aop:before pointcut-ref="runBefore" method="executeBefore" />
</aop:aspect>
</aop:config>


Abc class:

public class Abc {

public void checkCronExecution() {
log.info("Test Executed");
log.info("Test Executed");
}
}


Jkl class:

public class Jkl {
public void executeBefore() {
//certain validations
}
}

Answer

The clean way is to use Around advice instead of Before.

Update the aspect (and relevant configuration) to something like below

public class Jkl{
    public void executeAround(ProceedingJoinPoint pjp) {
       //certain validations
       if(isValid){
           // optionally enclose within try .. catch
           pjp.proceed();  // this line will invoke your advised method
       } else {
           // log something or do nothing
       }
    }
}
Comments