在Spring AOP中,我们可以使用@Around
注解来实现异常处理。下面是一个简单的例子,展示了如何使用AOP拦截器来处理方法执行过程中的异常。
public class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
@Component
public class TargetClass {
public void targetMethod() {
System.out.println("Target method executed");
throw new CustomException("An error occurred in the target method");
}
}
@Around
注解来处理异常:@Aspect
@Component
public class ExceptionHandlingAspect {
@Around("execution(* com.example.demo.TargetClass.*(..))")
public Object handleExceptions(ProceedingJoinPoint joinPoint) throws Throwable {
try {
// 执行目标方法
return joinPoint.proceed();
} catch (CustomException e) {
// 处理自定义异常
System.out.println("Handling custom exception: " + e.getMessage());
// 可以在这里添加其他异常处理逻辑,例如记录日志、发送通知等
} catch (Throwable t) {
// 处理其他未知异常
System.out.println("Handling unknown exception: " + t.getMessage());
}
return null;
}
}
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
@Autowired
private TargetClass targetClass;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
targetClass.targetMethod();
}
}
当运行此应用程序时,将看到以下输出:
Target method executed
Handling custom exception: An error occurred in the target method
这表明AOP拦截器已成功捕获并处理了目标方法中抛出的异常。