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
}
}
We anytime we want to disable aop auto-configuration, we can easily do by switching to spring. aop. auto to false .
In Spring AOP Before Advice is that executes before a join point i.e a method which annotated with AspectJ @Before annotation run exactly before the all methods matching with pointcut expression. But Before Advice does not have the ability to prevent execution flow proceeding to the join point.
Executing method on the target class Thus, Spring AOP injects a proxy instead of an actual instance of the target class. When we start the Spring or Spring Boot application, we see Spring executes the advice before the actual method.
JoinPoint: Joinpoint are points in your program execution where flow of execution got changed like Exception catching, Calling other method. PointCut: PointCut are basically those Joinpoints where you can put your advice(or call aspect). So basically PointCuts are the subset of JoinPoints.
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With