Spring Boot AOP之對請求的參數入參與返回結果進行攔截處理


Spring Boot AOP之對請求的參數入參與返回結果進行攔截處理

本文鏈接: https://blog.csdn.net/puhaiyang/article/details/78146620
 

spring Aop切面中的@Before @Around等執行順序與請求參數統一解碼

https://www.cnblogs.com/newAndHui/p/11771035.html

 

對於spring框架來說,最重要的兩大特性就是AOP 和IOC。

以前一直都知道有這兩個東西,在平時做的項目中也常常會涉及到這兩塊,像spring的事務管理什么的,在看了些源碼后,才知道原來事務管理也是用的AOP來實現的。對於IOC的話,平時接觸的就更多了,什么autowired,resource各種注解,就是IOC的各種應用。

一直我也想着能有機會自己動手寫個aop的小DEMO,不過一直沒機會,想到了許多,在網上一搜,基本上都已經有了。今天想到一個用於對service方法進行攔截的功能點,今天決定用springBoot的工程來實現一下。

功能點描述:對某個service的方法執行前,獲取出入參,對入參的參數進行修改,將參數進行替換。然后在這個方法執行完畢后,再對其返回結果進行修改。主要就是對一個方法裝飾一下。說到裝飾,第一想到的是采用裝飾器模式來實現,但裝飾器模式需要對整個代碼的結構進行一些修改,為了達到對以前的代碼不進行任何接觸,且裝飾器模式的局限性較小,所以最好還是用spring的AOP來實現這種對代碼無任何侵入的功能。

service的代碼如下:

 

@Service

public class TestServiceImpl implements TestService {

private Logger logger = LoggerFactory.getLogger(this.getClass());



@Override

public ResultVO getResultData(ParamVO paramVO) {

return process(paramVO);

}



private ResultVO process(ParamVO paramVO) {

logger.info("----->input INFO:{}", paramVO);

ResultVO resultVO = new ResultVO();

resultVO.setCode(200);

resultVO.setData(Arrays.asList("123", "456", "789"));

resultVO.setMessage("OK!!!!!!!! and your inputParam is" + paramVO.toString());

logger.info("---->return INFO:{}", resultVO.toString());

return resultVO;

}


 

其中入參為paramVO,代碼如下:

public class ParamVO {

private String inputParam;

private String inputParam2;

//getter and setter

}

 

返回的參數ResutVO,代碼如下:

 

 

  1.  
    public class ResultVO {
  2.  
    private Integer code;
  3.  
    private String message;
  4.  
    private Object data;
  5.  
    //getter and setter
  6.  
    }

其調用的入口為一個controller,代碼如下:

 

  1.  
    @RequestMapping(value = "test")
  2.  
    @RestController
  3.  
    public class TestController {
  4.  
    @Resource
  5.  
    private TestService testService;
  6.  
     
  7.  
    @GetMapping(value = "getResult")
  8.  
    public ResultVO getResult(ParamVO paramVO) {
  9.  
    ResultVO resultData = testService.getResultData(paramVO);
  10.  
    return resultData;
  11.  
    }

 

 

在正常情況下,按照如上的代碼進行調用將返回如下的信息:



通過返回的信息可以看到,入參是我們在請求參數傳入的inputParam=111和inputParam2=2220

現在要做的就是把入參的參數通過AOP來攔截,並進行修改。對於返回值,也進行一下修改。

首先讓工程引入AOP的包:

 

  1.  
    <!-- AOP -->
  2.  
    <dependency>
  3.  
    <groupId>org.springframework.boot</groupId>
  4.  
    <artifactId>spring-boot-starter-aop</artifactId>
  5.  
    </dependency>


 

然后定義一個Aspect,並指定一個切入點,配置要進行哪些方法的攔截

這里只針對TestSevice這個接口下的getResultData進行攔截

 

  1.  
    private final String ExpGetResultDataPonit = "execution(* com.haiyang.onlinejava.complier.service.TestService.getResultData(..))";
  2.  
     
  3.  
    //定義切入點,攔截servie包其子包下的所有類的所有方法
  4.  
    // @Pointcut("execution(* com.haiyang.onlinejava.complier.service..*.*(..))")
  5.  
    //攔截指定的方法,這里指只攔截TestService.getResultData這個方法
  6.  
    @Pointcut(ExpGetResultDataPonit)
  7.  
    public void excuteService() {
  8.  
     
  9.  
    }

對於切入點的配置表達式,可以在網上自行搜索,網上也有許多

 

在指定了切入點后,就可以對這個切入點excuteService()這個點進行相應的操作了。

可以配置@Before  @After 等來進行相應的處理,其代表的意思分別是前置與后置,就是下面代碼這個意思

 

  1.  
    @Override
  2.  
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  3.  
    Object result;
  4.  
    try {
  5.  
    //@Before
  6.  
    result = method.invoke(target, args);
  7.  
    //@After
  8.  
    return result;
  9.  
    } catch (InvocationTargetException e) {
  10.  
    Throwable targetException = e.getTargetException();
  11.  
    //@AfterThrowing
  12.  
    throw targetException;
  13.  
    } finally {
  14.  
    //@AfterReturning
  15.  
    }
  16.  
    }

由於要對入參和最終返回結果進行處理,所以選擇Before和AfterReturning,原來以為after也可以,但看了下,它好像並不能拿到這個方法的返回值,而AfterReturning是一定可以的

 

攔截后,對應的處理代碼如下:

 

  1.  
    //執行方法前的攔截方法
  2.  
    @Before("excuteService()")
  3.  
    public void doBeforeMethod(JoinPoint joinPoint) {
  4.  
    System.out.println( "我是前置通知,我將要執行一個方法了");
  5.  
    //獲取目標方法的參數信息
  6.  
    Object[] obj = joinPoint.getArgs();
  7.  
    for (Object argItem : obj) {
  8.  
    System.out.println( "---->now-->argItem:" + argItem);
  9.  
    if (argItem instanceof ParamVO) {
  10.  
    ParamVO paramVO = (ParamVO) argItem;
  11.  
    paramVO.setInputParam( "666666");
  12.  
    }
  13.  
    System.out.println( "---->after-->argItem:" + argItem);
  14.  
    }
  15.  
    }
  16.  
     
  17.  
    /**
  18.  
    * 后置返回通知
  19.  
    * 這里需要注意的是:
  20.  
    * 如果參數中的第一個參數為JoinPoint,則第二個參數為返回值的信息
  21.  
    * 如果參數中的第一個參數不為JoinPoint,則第一個參數為returning中對應的參數
  22.  
    * returning 限定了只有目標方法返回值與通知方法相應參數類型時才能執行后置返回通知,否則不執行,對於returning對應的通知方法參數為Object類型將匹配任何目標返回值
  23.  
    */
  24.  
    @AfterReturning(value = ExpGetResultDataPonit, returning = "keys")
  25.  
    public void doAfterReturningAdvice1(JoinPoint joinPoint, Object keys) {
  26.  
    System.out.println( "第一個后置返回通知的返回值:" + keys);
  27.  
    if (keys instanceof ResultVO) {
  28.  
    ResultVO resultVO = (ResultVO) keys;
  29.  
    String message = resultVO.getMessage();
  30.  
    resultVO.setMessage( "通過AOP把值修改了 " + message);
  31.  
    }
  32.  
    System.out.println( "修改完畢-->返回方法為:" + keys);
  33.  
    }

然后再請求一下之前的請求

 

 

從這里可以看出,通過AOP的攔截,已經把對應的值修改了,入參inputParam由111改成了666666,返回結果message也加上了幾個字

除了用Before和AfterReturning外,還可以用環繞來實現同樣的功能,如:

 

  1.  
    /**
  2.  
    * 環繞通知:
  3.  
    * 環繞通知非常強大,可以決定目標方法是否執行,什么時候執行,執行時是否需要替換方法參數,執行完畢是否需要替換返回值。
  4.  
    * 環繞通知第一個參數必須是org.aspectj.lang.ProceedingJoinPoint類型
  5.  
    */
  6.  
    @Around(ExpGetResultDataPonit)
  7.  
    public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint) {
  8.  
    System.out.println( "環繞通知的目標方法名:" + proceedingJoinPoint.getSignature().getName());
  9.  
    processInputArg(proceedingJoinPoint.getArgs());
  10.  
    try {//obj之前可以寫目標方法執行前的邏輯
  11.  
    Object obj = proceedingJoinPoint.proceed(); //調用執行目標方法
  12.  
    processOutPutObj(obj);
  13.  
    return obj;
  14.  
    } catch (Throwable throwable) {
  15.  
    throwable.printStackTrace();
  16.  
    }
  17.  
    return null;
  18.  
    }
  19.  
     
  20.  
    /**
  21.  
    * 處理返回對象
  22.  
    */
  23.  
    private void processOutPutObj(Object obj) {
  24.  
    System.out.println( "OBJ 原本為:" + obj.toString());
  25.  
    if (obj instanceof ResultVO) {
  26.  
    ResultVO resultVO = (ResultVO) obj;
  27.  
    resultVO.setMessage( "哈哈,我把值修改了" + resultVO.getMessage());
  28.  
    System.out.println(resultVO);
  29.  
    }
  30.  
    }
  31.  
     
  32.  
    /**
  33.  
    * 處理輸入參數
  34.  
    *
  35.  
    * @param args 入參列表
  36.  
    */
  37.  
    private void processInputArg(Object[] args) {
  38.  
    for (Object arg : args) {
  39.  
    System.out.println( "ARG原來為:" + arg);
  40.  
    if (arg instanceof ParamVO) {
  41.  
    ParamVO paramVO = (ParamVO) arg;
  42.  
    paramVO.setInputParam( "654321");
  43.  
    }
  44.  
    }
  45.  
    }

這樣寫,也可以達到相同的目的

 

 

切面代碼完整如下:

 

  1.  
    package com.haiyang.onlinejava.complier.aspect;
  2.  
     
  3.  
    import com.haiyang.onlinejava.complier.vo.ParamVO;
  4.  
    import com.haiyang.onlinejava.complier.vo.ResultVO;
  5.  
    import org.aspectj.lang.JoinPoint;
  6.  
    import org.aspectj.lang.ProceedingJoinPoint;
  7.  
    import org.aspectj.lang.annotation.*;
  8.  
    import org.springframework.context.annotation.Configuration;
  9.  
     
  10.  
    @Configuration
  11.  
    @Aspect
  12.  
    public class ServiceAspect {
  13.  
     
  14.  
    private final String ExpGetResultDataPonit = "execution(* com.haiyang.onlinejava.complier.service.TestService.getResultData(..))";
  15.  
     
  16.  
    //定義切入點,攔截servie包其子包下的所有類的所有方法
  17.  
    // @Pointcut("execution(* com.haiyang.onlinejava.complier.service..*.*(..))")
  18.  
    //攔截指定的方法,這里指只攔截TestService.getResultData這個方法
  19.  
    @Pointcut(ExpGetResultDataPonit)
  20.  
    public void excuteService() {
  21.  
     
  22.  
    }
  23.  
     
  24.  
    //執行方法前的攔截方法
  25.  
    // @Before("excuteService()")
  26.  
    public void doBeforeMethod(JoinPoint joinPoint) {
  27.  
    System.out.println( "我是前置通知,我將要執行一個方法了");
  28.  
    //獲取目標方法的參數信息
  29.  
    Object[] obj = joinPoint.getArgs();
  30.  
    for (Object argItem : obj) {
  31.  
    System.out.println( "---->now-->argItem:" + argItem);
  32.  
    if (argItem instanceof ParamVO) {
  33.  
    ParamVO paramVO = (ParamVO) argItem;
  34.  
    paramVO.setInputParam( "666666");
  35.  
    }
  36.  
    System.out.println( "---->after-->argItem:" + argItem);
  37.  
    }
  38.  
    }
  39.  
     
  40.  
    /**
  41.  
    * 后置返回通知
  42.  
    * 這里需要注意的是:
  43.  
    * 如果參數中的第一個參數為JoinPoint,則第二個參數為返回值的信息
  44.  
    * 如果參數中的第一個參數不為JoinPoint,則第一個參數為returning中對應的參數
  45.  
    * returning 限定了只有目標方法返回值與通知方法相應參數類型時才能執行后置返回通知,否則不執行,對於returning對應的通知方法參數為Object類型將匹配任何目標返回值
  46.  
    */
  47.  
    // @AfterReturning(value = ExpGetResultDataPonit, returning = "keys")
  48.  
    public void doAfterReturningAdvice1(JoinPoint joinPoint, Object keys) {
  49.  
    System.out.println( "第一個后置返回通知的返回值:" + keys);
  50.  
    if (keys instanceof ResultVO) {
  51.  
    ResultVO resultVO = (ResultVO) keys;
  52.  
    String message = resultVO.getMessage();
  53.  
    resultVO.setMessage( "通過AOP把值修改了 " + message);
  54.  
    }
  55.  
    System.out.println( "修改完畢-->返回方法為:" + keys);
  56.  
    }
  57.  
     
  58.  
     
  59.  
    /**
  60.  
    * 后置最終通知(目標方法只要執行完了就會執行后置通知方法)
  61.  
    */
  62.  
    // @After("excuteService()")
  63.  
    public void doAfterAdvice(JoinPoint joinPoint) {
  64.  
     
  65.  
    System.out.println( "后置通知執行了!!!!");
  66.  
    }
  67.  
     
  68.  
     
  69.  
     
  70.  
     
  71.  
    /**
  72.  
    * 環繞通知:
  73.  
    * 環繞通知非常強大,可以決定目標方法是否執行,什么時候執行,執行時是否需要替換方法參數,執行完畢是否需要替換返回值。
  74.  
    * 環繞通知第一個參數必須是org.aspectj.lang.ProceedingJoinPoint類型
  75.  
    */
  76.  
    @Around(ExpGetResultDataPonit)
  77.  
    public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint) {
  78.  
    System.out.println( "環繞通知的目標方法名:" + proceedingJoinPoint.getSignature().getName());
  79.  
    processInputArg(proceedingJoinPoint.getArgs());
  80.  
    try {//obj之前可以寫目標方法執行前的邏輯
  81.  
    Object obj = proceedingJoinPoint.proceed(); //調用執行目標方法
  82.  
    processOutPutObj(obj);
  83.  
    return obj;
  84.  
    } catch (Throwable throwable) {
  85.  
    throwable.printStackTrace();
  86.  
    }
  87.  
    return null;
  88.  
    }
  89.  
     
  90.  
    /**
  91.  
    * 處理返回對象
  92.  
    */
  93.  
    private void processOutPutObj(Object obj) {
  94.  
    System.out.println( "OBJ 原本為:" + obj.toString());
  95.  
    if (obj instanceof ResultVO) {
  96.  
    ResultVO resultVO = (ResultVO) obj;
  97.  
    resultVO.setMessage( "哈哈,我把值修改了" + resultVO.getMessage());
  98.  
    System.out.println(resultVO);
  99.  
    }
  100.  
    }
  101.  
     
  102.  
    /**
  103.  
    * 處理輸入參數
  104.  
    *
  105.  
    * @param args 入參列表
  106.  
    */
  107.  
    private void processInputArg(Object[] args) {
  108.  
    for (Object arg : args) {
  109.  
    System.out.println( "ARG原來為:" + arg);
  110.  
    if (arg instanceof ParamVO) {
  111.  
    ParamVO paramVO = (ParamVO) arg;
  112.  
    paramVO.setInputParam( "654321");
  113.  
    }
  114.  
    }
  115.  
    }
  116.  
     
  117.  
     
  118.  
    }

 

如不進行@Before和@AfterReturing的注釋,最終的結果如下:

控制台打印的日志為:

通過查看打印的結果,我們可以知道@Around @Before  @After  @AfterReturning這幾個注解的執行順序為:

Around
AroundBefore
  before
  method.invoke()
  AroundAfter
      After
AfterReturning

 

主要參考:http://blog.csdn.net/zknxx/article/details/53240959


免責聲明!

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



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