如何在 Spring AOP 中停止方法执行
How to stop method execution in Spring AOP
我创建了一个名为 BaseCron 的 bean,它有一个方法 executeBefore()
,在下面的 spring 配置中配置,以拦截 Crons class 的所有方法调用并在之前执行他们。
executeBefore()
方法有一些验证。我早些时候验证了某些条件,如果它们是假的,我就会抛出异常。这种异常抛出导致方法失败,因此 Crons class 中的方法没有执行。
工作正常。
你能建议我可以停止执行 Crons class 而不会抛出异常的其他方法吗?我试过 return 但没有成功。
<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
}
}
干净的方法是使用 Around
通知而不是 Before
。
将方面(和相关配置)更新为如下所示
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
}
}
}
我创建了一个名为 BaseCron 的 bean,它有一个方法 executeBefore()
,在下面的 spring 配置中配置,以拦截 Crons class 的所有方法调用并在之前执行他们。
executeBefore()
方法有一些验证。我早些时候验证了某些条件,如果它们是假的,我就会抛出异常。这种异常抛出导致方法失败,因此 Crons class 中的方法没有执行。
工作正常。
你能建议我可以停止执行 Crons class 而不会抛出异常的其他方法吗?我试过 return 但没有成功。
<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
}
}
干净的方法是使用 Around
通知而不是 Before
。
将方面(和相关配置)更新为如下所示
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
}
}
}