Spring aop 实现异常拦截

时间:2023-03-09 03:52:44
Spring aop 实现异常拦截

使用aop异常挂载功能可以统一处理方法抛出的异常,减少很多重复代码,实现如下:

1、实现ThrowAdvice

 public class ExceptionHandler implements ThrowsAdvice {

     private static Logger LOGGER = LoggerFactory.getLogger(ExceptionHandler.class);

     public void afterThrowing(Exception e) throws Throwable {
LOGGER.debug("exception 来了!");
}
}

2、在application.xml文件中配置

     <bean id="exceptionHandler" class="com.lz.cgw.api.service.exception.ExceptionHandler" />

     <aop:config>
<aop:aspect ref="exceptionHandler">
<aop:pointcut id="exceptionService" expression="execution(* com.lz.cgw.api.service.ApiUserServiceImpl.*(..))" />
<aop:after-throwing pointcut-ref="exceptionService" method="afterThrowing" throwing="e" />
</aop:aspect>
</aop:config>

注意一下不要漏了throwing配置,且参数名称要去advice中的一置,否则绑定会报错。