Springboot打印接口的三種方式分享
1 aop切面的方式
1.1 實現(xiàn)思路
- 引入aop依賴
- 自定義注解
- 定義切面,采用環(huán)繞通知
1.2 代碼實現(xiàn)
1)引入依賴
<!--aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>2)自定義注解LogAnnotation
/**
* 日志注解
* METHOD 方法上 type 類上
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {
/**
* 模塊
*/
String module() default "";
/**
* 簡單描述接口的作用
*/
String operation() default "";
}3)定義切面
簡單分析一下切面實現(xiàn)的功能:
/**
* @author : look-word
* 2022-07-27 16:03
**/
@Slf4j
@Aspect
@Component
public class LogAspect {
/**
* 切入點
*/
@Pointcut("@annotation(look.word.reggie.common.aop.LogAnnotation)")
public void logPointCut() {
}
/**
* 環(huán)繞通知
*
* @param point 連接點
*/
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
//執(zhí)行方法
Object result = point.proceed();
//執(zhí)行時長(毫秒)
long time = System.currentTimeMillis() - beginTime;
//保存日志
recordLog(point, time);
return result;
}
private void recordLog(ProceedingJoinPoint joinPoint, long time) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
// 獲取當前方法
Method method = signature.getMethod();
LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
log.info("=====================log start================================");
log.info("module:{}", logAnnotation.module());
log.info("operation:{}", logAnnotation.operation());
//請求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
log.info("request method:{}", className + "." + methodName + "()");
//請求的參數(shù)
Object[] args = joinPoint.getArgs();
Stream<?> stream = ArrayUtils.isEmpty(args) ? Stream.empty() : Arrays.stream(args);
List<Object> logArgs =
stream.filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse))).collect(Collectors.toList());
String params = JSON.toJSONString(logArgs);
log.info("params:{}", params);
//獲取request 設(shè)置IP地址
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
log.info("ip:{}", IpUtils.getIpAddr(request));
log.info("execute time : {} ms", time);
log.info("=====================log end================================");
}
}1.3 功能測試
在接口上添加注解即可,還有描述信息


2 過濾器的方式
這種方式簡單點 但是可配置性不高
注意:一定得掃描到spring容器中
創(chuàng)建一個類 實現(xiàn) filter接口
- init:該方法是對filter對象進行初始化的方法,僅在容器初始化filter對象結(jié)束后被調(diào)用一次,參數(shù)FilterConfig可以獲得filter的初始化參數(shù);
- doFilter:可以對request和response進行
<u>預(yù)處理</u>。其中FilterChain可以將處理后的request和response對象傳遞到過濾鏈上的下一個資源。 - destroy():該方法在容器銷毀對象前被調(diào)用。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Component
public class LogFilter implements Filter {
private static final Logger LOG = LoggerFactory.getLogger(LogFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// 打印請求信息
HttpServletRequest request = (HttpServletRequest) servletRequest;
LOG.info("------------- LogFilter 開始 -------------");
LOG.info("請求地址: {} {}", request.getRequestURL().toString(), request.getMethod());
LOG.info("遠程地址: {}", request.getRemoteAddr());
long startTime = System.currentTimeMillis();
filterChain.doFilter(servletRequest, servletResponse);
LOG.info("------------- LogFilter 結(jié)束 耗時:{} ms -------------", System.currentTimeMillis() - startTime);
}
}結(jié)果

總結(jié)
1.過濾器用來實現(xiàn)通用的功能,減少代碼冗余,提高可維護性;
2.一個過濾器可以配置給多個資源使用(編碼過濾器);
3.一個資源也可以配置多個過濾器,按照配置順序調(diào)用。
3 攔截器的方式
如果不懂 請先看了 介紹再來
話不說多 直接上代碼
創(chuàng)建攔截器
/**
* 攔截器:Spring框架特有的,常用于登錄校驗,權(quán)限校驗,請求日志打印 /login
* @author : look-word
* 2022-06-26 13:55
**/
@Component
public class LogInterceptor implements HandlerInterceptor {
private static final Logger LOG = LoggerFactory.getLogger(LogInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 打印請求信息
LOG.info("------------- LogInterceptor 開始 -------------");
LOG.info("請求地址: {} {}", request.getRequestURL().toString(), request.getMethod());
LOG.info("遠程地址: {}", request.getRemoteAddr());
long startTime = System.currentTimeMillis();
request.setAttribute("requestStartTime", startTime);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
long startTime = (Long) request.getAttribute("requestStartTime");
LOG.info("------------- LogInterceptor 結(jié)束 耗時:{} ms -------------", System.currentTimeMillis() - startTime);
}
}注冊攔截器
把我們的攔截器 注冊到 攔截器鏈中
/**
* @author : look-word
* 2022-06-26 14:03
**/
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {
@Resource
private LogInterceptor logInterceptor;
/**
* 注冊攔截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry
.addInterceptor(logInterceptor)
.addPathPatterns("/**")// 對那些接口攔截
.excludePathPatterns("/login");// 對哪些接機口放行
WebMvcConfigurer.super.addInterceptors(registry);
}
}測試結(jié)果

到此這篇關(guān)于Springboot打印接口的三種方式分享的文章就介紹到這了,更多相關(guān)Springboot打印接口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺談System.getenv()和System.getProperty()的區(qū)別
這篇文章主要介紹了System.getenv()和System.getProperty()的區(qū)別,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06
SpringBoot在IDEA中實現(xiàn)熱部署的步驟
這篇文章主要介紹了SpringBoot在IDEA中實現(xiàn)熱部署的步驟,幫助大家更好的理解和使用springboot框架,感興趣的朋友可以了解下2020-11-11
基于Java?利用Mybatis實現(xiàn)oracle批量插入及分頁查詢
這篇文章主要介紹了基于Java?利用Mybatis實現(xiàn)oracle批量插入及分頁查詢,文章圍繞主題展開詳細的內(nèi)容介紹,需要的小伙伴可以參考一下2022-07-07
Java把Map轉(zhuǎn)為對象的實現(xiàn)代碼
在項目開發(fā)中,經(jīng)常碰到map轉(zhuǎn)實體對象或者對象轉(zhuǎn)map的場景,工作中,很多時候我們可能比較喜歡使用第三方j(luò)ar包的API對他們進行轉(zhuǎn)化,但這里,我想通過反射的方式對他們做轉(zhuǎn)化,感興趣的同學跟著小編來看看吧2023-08-08

