这是我创建的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类,它有一个抛出错误的方法,我正在尝试使用我的@trafficFortuneservuce建议来捕捉这个错误。
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";
}
}这是我的main方法类,我在其中运行我的应用程序。
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)发布于 2021-01-09 15:46:52
向您的spring配置类添加@EnableAspectJAutoProxy (添加到MyAroundAspect.java就可以了)。
Spring Boot会像here中描述的那样用@SpringBootApplication自动打开这个功能,所以在普通的spring boot应用程序中,没有必要手动标记这个注释。但在您的示例中,您是手动启动应用程序的,因此它不起作用。
发布于 2021-01-09 17:35:22
不要将您的普通应用程序类设置为@Aspect。首先,它没有任何意义。其次,Spring AOP方面不能相互建议,因此您实际上是在阻止自己实现目标,搬起石头砸自己的脚。
更新:我说的是这个:
//@Aspect <-- You got to get rid of this, the serice is not an aspect!
@Component
public class TrafficFortuneService {
// (...)
}https://stackoverflow.com/questions/65639913
复制相似问题