Spring Aop 异常

本文记录了使用Spring 3.0.3进行AOP测试时遇到的问题及解决过程。主要原因是缺少aopalliance.jar包导致无法实例化相关Bean。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.config.internalAutoProxyCreator': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean

 

     用Spring3.0.3做测试aop用例时遇到的异常(由于Spring3.0并没有提供aspect相关的jar,于是使用Spring2.0的aspect包),看了N多的网页说是要换成Spring 2.0.8或Spring 2.5.6 aspect包,结果一试还是出异常,最后没办法一个一个jar包添加进去才发现是少了aopalliance.jar包。

### Spring AOP异常处理的方法 在 Spring AOP 应用程序中,可以通过多种方式来捕获和处理异常。一种常见的方式是在切面中定义 `@AfterThrowing` 通知,用于捕捉特定类型的异常并执行相应的逻辑。 #### 使用 `@AfterThrowing` 处理异常 当被拦截的方法抛出指定类型的异常时,`@AfterThrowing` 切入点会触发。这允许开发者编写专门针对异常情况的业务逻辑[^1]。 ```java import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; @Aspect public class ExceptionHandlingAspect { @AfterThrowing(pointcut = "execution(* com.example.service.*.*(..))", throwing = "ex") public void logException(Exception ex){ System.err.println("An exception has been caught: " + ex.getMessage()); } } ``` 这段代码展示了如何创建一个简单的方面,在任何服务层方法抛出异常时记录错误消息。通过设置 `throwing` 属性,可以访问实际发生的异常对象。 #### 统一异常处理器 除了利用 AOP 来管理异常外,还可以采用全局异常处理器来进行更全面的控制。例如,使用控制器建议 (`ControllerAdvice`) 可以为整个应用程序提供一致性的异常响应机制[^4]。 ```java @Slf4j @ResponseBody @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ArithmeticException.class) public ResponseEntity<String> handleArithmeticException(){ return new ResponseEntity<>("Divide by zero error.", HttpStatus.BAD_REQUEST); } @ExceptionHandler(NullPointerException.class) public ResponseEntity<String> handleNullPointerExeption(){ return new ResponseEntity<>("Null pointer encountered.", HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(RuntimeException.class) public ResponseEntity<String> handleRuntimeException(){ return new ResponseEntity<>("Runtime exception occurred.", HttpStatus.INTERNAL_SERVER_ERROR); } } ``` 此示例说明了如何为不同种类的运行时异常配置自定义的消息返回给客户端,并且可以根据 HTTP 状态码区分不同的错误级别。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值