Salman Kazmi Salman Kazmi - 1 year ago 193
Java Question

How to stop method execution in Spring AOP

I have created a bean named BaseCron that has a method

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

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">
<aop:aspect id="cron" ref="baseCronBean">
<aop:pointcut id="runBefore" expression="execution(* com.myapp.cron.Abc.*.*(..)) " />
<aop:before pointcut-ref="runBefore" method="executeBefore" />

Abc class:

public class Abc {

public void checkCronExecution() {"Test Executed");"Test Executed");

Jkl class:

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

Answer Source

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
           // optionally enclose within try .. catch
           pjp.proceed();  // this line will invoke your advised method
       } else {
           // log something or do nothing
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download