java无法运行@Advice catch异常块
这是我创建的Aop特性,用于在我的主应用程序抛出错误后运行
package com.demo.aspects;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class MyAroundAspect {
@Around("execution(* com.demo.aop.*.getFortune(..))")
public Object aroundAdviceDemo(ProceedingJoinPoint thePJP) throws Throwable
{
System.out.println("run this before the fortune method");
Object result = null;
try {
result = thePJP.proceed();
}
catch(Exception exc)
{ //this should run but is not running
System.out.println("Catching the " + exc.getMessage());
}
System.out.println("Run this after the fortune service");
return result;
}
}
这是我的trafficFortuneservuce类,它有一个抛出错误的方法,我正在尝试使用@Around建议捕获该错误
package com.demo.aop;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class TrafficFortuneService {
public String getFortune(boolean tripwire)
{
if(tripwire)
{ //this is running but it should go to the advice catch block
throw new RuntimeException("Inside run time exception in the fortune service");
}
return "Today is your lucky day";
}
}
这是我运行应用程序的主要方法类
package com.demo.aop.app;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.demo.aop.Account;
import com.demo.aop.AccountDAO;
import com.demo.aop.AppConfig;
import com.demo.aop.MemberDAO;
import com.demo.aop.TrafficFortuneService;
public class AroundDemoApp {
public static void main(String[] args) {
//Getting context object
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
TrafficFortuneService theService = context.getBean("trafficFortuneService", TrafficFortuneService.class);
boolean tripwire = true;
String temp = theService.getFortune(tripwire);
System.out.println(temp);
context.close();
}
}
这里是输出,它正在打印我在trafficfortuneservice
类中声明的消息
Exception in thread "main" java.lang.RuntimeException: Inside run time exception in the fortune service
at com.demo.aop.TrafficFortuneService.getFortune(TrafficFortuneService.java:15)
at com.demo.aop.app.AroundDemoApp.main(AroundDemoApp.java:20)
# 1 楼答案
不要将普通的应用程序类设置为
@Aspect
。首先,这毫无意义。其次,Spring AOP方面不能相互建议,所以你实际上是在阻止自己实现目标,朝自己的脚开枪更新:我说的是:
# 2 楼答案
将
@EnableAspectJAutoProxy
添加到spring配置类(添加到MyAroundAspect.java
是可以的)Spring Boot将自动使用
@SpringBootApplication
打开此函数,如here所述,因此在正常的Spring Boot应用程序中,不必手动标记此注释。但在您的情况下,您是手动启动应用程序的,因此无法正常工作