日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
使用Spring的AOP打印HTTP接口出入?yún)⑷罩?/div>

前言

最近在維護一個運營端的系統(tǒng),和前端聯(lián)調(diào)的過程中,經(jīng)常需要排查一些交互上的問題,每次都得看前端代碼的傳參和后端代碼的出參,于是打算給HTTP接口加上出入?yún)⑷罩尽?/p>

但看著目前的HTTP接口有點多,那么有什么快捷的方式呢?答案就是實用Spring的AOP功能,簡單實用。

思路

定義個一個SpringAOP的配置類,里邊獲取請求的URL、請求的入?yún)?、相?yīng)的出參,通過日志打印出來。

SpringBoot的aop依賴:


org.springframework.boot
spring-boot-starter-aop

示例

1.編寫一個HTTP接口

定義了一個Controller,里邊就一個方法,方法請求類型是get,出入?yún)⒍际呛唵蔚囊粋€字符串字段。

package com.example.springbootaoplog.controller;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* @author hongcunlin
*/
@RestController
@RequestMapping("/index")
public class IndexController {

@GetMapping("/indexContent")
public String indexContent(String param) {
return "test";
}
}

2.編寫一個AOP日志配置

這算是本文的重點了,定義一個AOP的內(nèi)容,首先是切點,再者是請求前日志打印,最后請求后日志打印

package com.example.springbootaoplog.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
* aop日志打印配置
*
* @author hongcunlin
*/
@Slf4j
@Aspect
@Component
public class AopLogConfig {
/**
* 切點路徑:Controller層的所有方法
*/
@Pointcut("execution(public * com.example.springbootaoplog.controller.*.*(..))")
public void methodPath() {
}

/**
* 入?yún)?br> *
* @param joinPoint 切點
*/
@Before(value = "methodPath()")
public void before(JoinPoint joinPoint) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String url = requestAttributes.getRequest().getRequestURL().toString();
log.info("請求 = {}, 入?yún)?= {}", url, JSON.toJSONString(joinPoint.getArgs()));
}

/**
* 出參
*
* @param res 返回
*/
@AfterReturning(returning = "res", pointcut = "methodPath()")
public void after(Object res) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
String url = requestAttributes.getRequest().getRequestURL().toString();
log.info("請求 = {}, 入?yún)?= {}", url, JSON.toJSONString(res));
}
}

3.結(jié)果測試

我們通過瀏覽器的URL,針對我們編寫的http接口,發(fā)起一次get請求:

可以看到,日志里邊打印了我們預(yù)期的請求的URL和出入?yún)⒘耍?/p>

說明我們的程序是正確的了。

最后

本文分享了通過Spring的AOP功能,完成HTTP接口的出入?yún)⑷罩镜拇蛴〉姆椒?,同時也說明,越是基礎(chǔ)的東西,越是實用。


本文名稱:使用Spring的AOP打印HTTP接口出入?yún)⑷罩?
文章出自:http://www.5511xx.com/article/dpppgih.html