在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攔截器已成功捕獲并處理了目標方法中拋出的異常。