有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在SpringAOP中停止方法执行

我创建了一个名为BaseCron的bean,它有一个方法executeBefore(),该方法在下面的spring配置中配置为拦截Crons类的所有方法调用,并在它们之前执行

executeBefore()方法有一些验证。我之前在验证某些条件,如果它们是假的,我会抛出一个异常。抛出异常导致方法失败,因此Crons类中的方法没有执行

它运转良好

你能不能建议一些其他方法,让我停止Crons类的执行,而不引发异常。我试着返回,但没有成功

<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课程:

public class Abc {

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

Jkl课程:

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

共 (1) 个答案

  1. # 1 楼答案

    干净的方法是使用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
           }
        }
    }