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中的一置,否則綁定會報錯。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM