Spring AOP 後置通知修改響應httpstatus方式
Spring AOP後置通知修改響應httpstatus
1.定義Aspect
/** * 響應體切面 * 後置通知修改httpstatus * * @author : CatalpaFlat */ @Component @Aspect public class ApiResponseAspect { private Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 切面 */ private final String POINT_CUT = "execution(* com.xxx.web.controller..*(..))"; @Pointcut(POINT_CUT) private void pointcut() { } @AfterReturning(value = POINT_CUT, returning = "apiResponse", argNames = "apiResponse") public void doAfterReturningAdvice2(ApiResponse apiResponse) { logger.info("apiResponse:" + apiResponse); Integer state = apiResponse.getState(); if (state != null) { ServletRequestAttributes res = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); res.getResponse().setStatus(state); } } }
2.使用
2.1.請求體
return ApiUtil.error(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(),"the request body is empty");
2.2.參數缺失
return ApiUtil.error(HttpStatus.BAD_REQUEST.value(),"Parameter id is empty");
2.3.權限認證
return ApiUtil.error(HttpStatus.UNAUTHORIZED.value(),"Current requests need user validation");
2.4.與資源存在沖突
return ApiUtil.error(HttpStatus.CONFLICT.value(),"Conflict with resources");
2.5.攜帶error信息
return ApiUtil.error(HttpStatus.BAD_REQUEST.value(),"There are some mistakes",obj);
3.ApiResponse響應體
public class ApiResponse { private Integer state; private String message; private Object result; private Object error; }
4.ApiUtil
public class ApiUtil { /** * http回調錯誤 */ public static ApiResponse error(Integer code, String msg) { ApiResponse result = new ApiResponse(); result.setState(code); result.setMessage(msg); return result; } /** * http回調錯誤 */ public static ApiResponse error(Integer code, String msg,Object error) { ApiResponse result = new ApiResponse(); result.setState(code); result.setMessage(msg); result.setError(error); return result; } }
Spring AOP前後置通知最簡單案例
僅僅針對於spring
案例分析:
- 該案例執行Demo類中的三個方法,分別輸出Demo1,Demo2,Demo3
- 我們以Demo2為切點,分別執行前置通知和後置通知
1.首先導jar包
2.寫applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 將Demo放入bean容器中 --> <bean id="demo" class="com.hym.bean.Demo"></bean> <!-- 將前置通知和後置通知也放入到bean容器中 id 自己任意取,後續引用就取id ,class是全類名 --> <bean id ="myBefore" class="com.hym.advice.MyBeforeAdvice"></bean> <bean id ="myAfter" class="com.hym.advice.MyAfterAdvice"></bean> <aop:config> <!-- 圍繞的哪一個切點進行前後置通知 execution(* 全類名+方法名 ) 這是固定寫法 id 自己取名,後續引用就取id--> <aop:pointcut expression="execution(* com.hym.bean.Demo.Demo2())" id="mypoint"/> <!-- 通知 根據advice-ref中的值 來區分是前置通知還是後置通知 。 值就是前後置通知的id pointcut-ref 是切點的id--> <aop:advisor advice-ref="myBefore" pointcut-ref="mypoint"/> <aop:advisor advice-ref="myAfter" pointcut-ref="mypoint"/> </aop:config> <!-- r如果存在兩個參數,name和id 那麼用以下的寫法 --> <!-- <aop:config> <aop:pointcut expression="execution(* com.hym.bean.Demo.Demo2(String,int) and args(name,id)) " id=""/> </aop:config> --> </beans>
3.項目架構
4.Demo類
package com.hym.bean; public class Demo { public void Demo1() { System.out.println("Demo1"); } public void Demo2() { System.out.println("Demo2"); } public void Demo3() { System.out.println("Demo3"); } }
5.前後置通知
前置通知:
類中方法需要實現MethodBeforeAdvice
package com.hym.advice; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; public class MyAfterAdvice implements AfterReturningAdvice{ @Override public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable { System.out.println("執行後置通知"); } }
後置通知:
類中方法需要實現AfterReturningAdvice
該接口命名規范與前置通知有差異,需註意
package com.hym.advice; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; public class MyAfterAdvice implements AfterReturningAdvice{ @Override public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable { System.out.println("執行後置通知"); } }
最後測試類:
package com.hym.test; import org.apache.catalina.core.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.hym.bean.Demo; public class Test { public static void main(String[] args) { ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); Demo demo = ac.getBean("demo",Demo.class); demo.Demo1(); demo.Demo2(); demo.Demo3(); } }
最終執行結果:
AOP:面向切面編程
在執行Demo時,是縱向執行的,先Demo1,Demo2,Demo3.
但是我們以Demo2為切點,添加瞭前後置通知,這三個形成瞭一個橫向的切面過程。
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。
推薦閱讀:
- Spring框架實現AOP的兩種方式詳解
- Spring基於AspectJ的AOP開發案例解析
- 帶你瞭解Spring AOP的使用詳解
- 基於Spring depends-on的使用詳解
- 一篇文章教帶你瞭解Java Spring之自動裝配