Spring aop 实现异常拦截

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

1、实现ThrowAdvice

1 public class ExceptionHandler implements ThrowsAdvice {
2 
3     private static Logger LOGGER = LoggerFactory.getLogger(ExceptionHandler.class);
4 
5     public void afterThrowing(Exception e) throws Throwable {
6         LOGGER.debug("exception 来了!");
7     }
8 }

2、在application.xml文件中配置

1     <bean id="exceptionHandler" class="com.lz.cgw.api.service.exception.ExceptionHandler" />
2 
3     <aop:config>
4         <aop:aspect ref="exceptionHandler">
5             <aop:pointcut id="exceptionService" expression="execution(* com.lz.cgw.api.service.ApiUserServiceImpl.*(..))" />
6             <aop:after-throwing pointcut-ref="exceptionService" method="afterThrowing" throwing="e" />
7         </aop:aspect>
8     </aop:config>

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

posted @ 2015-03-11 16:25  涂墨留香  阅读(14152)  评论(1编辑  收藏  举报