詳解SpringBoot中的統(tǒng)一功能處理的實現(xiàn)
前言
接下來是 Spring Boot 統(tǒng)?功能處理模塊了,也是 AOP 的實戰(zhàn)環(huán)節(jié),要實現(xiàn)的課程?標(biāo)有以下 3 個:
- 統(tǒng)??戶登錄權(quán)限驗證
- 統(tǒng)?數(shù)據(jù)格式返回
- 統(tǒng)?異常處理
接下我們?個?個來看。
一、用戶登錄權(quán)限效驗
?戶登錄權(quán)限的發(fā)展從之前每個?法中??驗證?戶登錄權(quán)限,到現(xiàn)在統(tǒng)?的?戶登錄驗證處理,它是?個逐漸完善和逐漸優(yōu)化的過程。
1.1 最初的用戶登錄驗證
我們先來回顧?下最初?戶登錄驗證的實現(xiàn)?法:
@RestController
@RequestMapping("/user")
public class UserController {
/**
* 某?法 1
*/
@RequestMapping("/m1")
public Object method(HttpServletRequest request) {
// 有 session 就獲取,沒有不會創(chuàng)建
HttpSession session = request.getSession(false);
if (session != null && session.getAttribute("userinfo") != null) {
// 說明已經(jīng)登錄,業(yè)務(wù)處理
return true;
} else {
// 未登錄
return false;
}
}
/**
* 某?法 2
*/
@RequestMapping("/m2")
public Object method2(HttpServletRequest request) {
// 有 session 就獲取,沒有不會創(chuàng)建
HttpSession session = request.getSession(false);
if (session != null && session.getAttribute("userinfo") != null) {
// 說明已經(jīng)登錄,業(yè)務(wù)處理
return true;
} else {
// 未登錄
return false;
}
}
// 其他?法...
}從上述代碼可以看出,每個?法中都有相同的?戶登錄驗證權(quán)限,它的缺點是:
- 每個?法中都要單獨寫?戶登錄驗證的?法,即使封裝成公共?法,也?樣要傳參調(diào)?和在?法中進(jìn)?判斷。
- 添加控制器越多,調(diào)??戶登錄驗證的?法也越多,這樣就增加了后期的修改成本和維護(hù)成本。
- 這些?戶登錄驗證的?法和接下來要實現(xiàn)的業(yè)務(wù)?何沒有任何關(guān)聯(lián),但每個?法中都要寫?遍。
所以提供?個公共的 AOP ?法來進(jìn)?統(tǒng)?的?戶登錄權(quán)限驗證迫在眉睫。
1.2 Spring AOP 用戶統(tǒng)一登錄驗證的問題
說到統(tǒng)?的?戶登錄驗證,我們想到的第?個實現(xiàn)?案是 Spring AOP 前置通知或環(huán)繞通知來實現(xiàn),具體實現(xiàn)代碼如下:
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class UserAspect {
// 定義切點?法 controller 包下、?孫包下所有類的所有?法
@Pointcut("execution(* com.example.demo.controller..*.*(..))")
public void pointcut(){ }
// 前置?法
@Before("pointcut()")
public void doBefore(){
}
// 環(huán)繞?法
@Around("pointcut()")
public Object doAround(ProceedingJoinPoint joinPoint){
Object obj = null;
System.out.println("Around ?法開始執(zhí)?");
try {
// 執(zhí)?攔截?法
obj = joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("Around ?法結(jié)束執(zhí)?");
return obj;
}
}
如果要在以上 Spring AOP 的切?中實現(xiàn)?戶登錄權(quán)限效驗的功能,有以下兩個問題:
1.沒辦法獲取到 HttpSession 對象。
2.我們要對?部分?法進(jìn)?攔截,?另?部分?法不攔截,如注冊?法和登錄?法是不攔截的,這樣的話排除?法的規(guī)則很難定義,甚?沒辦法定義。
那這樣如何解決呢?
1.3 Spring 攔截器
對于以上問題 Spring 中提供了具體的實現(xiàn)攔截器:HandlerInterceptor,攔截器的實現(xiàn)分為以下兩個步驟:
1.創(chuàng)建?定義攔截器,實現(xiàn) HandlerInterceptor 接?的 preHandle(執(zhí)?具體?法之前的預(yù)處理)?法。
2.將?定義攔截器加? WebMvcConfigurer 的 addInterceptors ?法中。
具體實現(xiàn)如下。
補充 過濾器:
過濾器是Web容器提供的。觸發(fā)的時機比攔截器更靠前,Spring 初始化前就執(zhí)行了,所以并不能處理用戶登錄權(quán)限效驗等問題。
1.3.1 準(zhǔn)備工作
package com.example.demo.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@RequestMapping("/login")
public boolean login(HttpServletRequest request,
String username, String password) {
// // 1.非空判斷
// if (username != null && username != "" &&
// password != null && username != "") {
// // 2.驗證用戶名和密碼是否正確
// }
// 1.非空判斷
if (StringUtils.hasLength(username) && StringUtils.hasLength(password)) {
// 2.驗證用戶名和密碼是否正確
if ("admin".equals(username) && "admin".equals(password)) {
// 登錄成功
HttpSession session = request.getSession();
session.setAttribute("userinfo", "admin");
return true;
} else {
// 用戶名或密碼輸入錯誤
return false;
}
}
return false;
}
@RequestMapping("/getinfo")
public String getInfo() {
log.debug("執(zhí)行了 getinfo 方法");
return "執(zhí)行了 getinfo 方法";
}
@RequestMapping("/reg")
public String reg() {
log.debug("執(zhí)行了 reg 方法");
return "執(zhí)行了 reg 方法";
}
}
1.3.2 自定義攔截器
接下來使?代碼來實現(xiàn)?個?戶登錄的權(quán)限效驗,?定義攔截器是?個普通類,具體實現(xiàn)代碼如下:
package com.example.demo.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 登錄攔截器
*/
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 登錄判斷業(yè)務(wù)
HttpSession session = request.getSession(false);
if (session != null && session.getAttribute("userinfo") != null) {
return true;
}
log.error("當(dāng)前用戶沒有訪問權(quán)限");
response.setStatus(401);
return false;
}
}
返回 boolean 類型。
相當(dāng)于一層安保:
為 false 則不能繼續(xù)往下執(zhí)行;為 true 則可以。

1.3.3 將自定義攔截器加入到系統(tǒng)配置
將上?步中的?定義攔截器加?到系統(tǒng)配置信息中,具體實現(xiàn)代碼如下:
package com.example.demo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration // 一定不要忘記
public class MyConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor)
.addPathPatterns("/**") // 攔截所有請求
.excludePathPatterns("/user/login") // 排除不攔截的 url
// .excludePathPatterns("/**/*.html")
// .excludePathPatterns("/**/*.js")
// .excludePathPatterns("/**/*.css")
.excludePathPatterns("/user/reg"); // 排除不攔截的 url
}
}
或者:
package com.example.demo.common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class AppConfig implements WebMvcConfigurer {
// 不攔截的 url 集合
List<String> excludes = new ArrayList<String>() {{
add("/**/*.html");
add("/js/**");
add("/editor.md/**");
add("/css/**");
add("/img/**"); // 放行 static/img 下的所有文件
add("/user/login"); // 放行登錄接口
add("/user/reg"); // 放行注冊接口
add("/art/detail"); // 放行文章詳情接口
add("/art/list"); // 放行文章分頁列表接口
add("/art/totalpage"); // 放行文章分頁總頁數(shù)接口
}};
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 配置攔截器
InterceptorRegistration registration =
registry.addInterceptor(loginInterceptor);
registration.addPathPatterns("/**");
registration.excludePathPatterns(excludes);
}
}
如果不注入對象的話,addInterceptor() 的參數(shù)也可以直接 new 一個對象:
@Configuration // 一定不要忘記
public class MyConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**") // 攔截所有請求
.excludePathPatterns("/user/login") // 排除不攔截的 url
// .excludePathPatterns("/**/*.html")
// .excludePathPatterns("/**/*.js")
// .excludePathPatterns("/**/*.css")
// .excludePathPatterns("/**/*.jpg")
// .excludePathPatterns("/**/login")
.excludePathPatterns("/user/reg"); // 排除不攔截的 url
}
}
其中:
addPathPatterns:表示需要攔截的 URL,“**”表示攔截任意?法(也就是所有?法)。
excludePathPatterns:表示需要排除的 URL。
說明:以上攔截規(guī)則可以攔截此項?中的使? URL,包括靜態(tài)?件 (圖??件、JS 和 CSS 等?件)。
1.4 攔截器實現(xiàn)原理
正常情況下的調(diào)?順序:

然?有了攔截器之后,會在調(diào)? Controller 之前進(jìn)?相應(yīng)的業(yè)務(wù)處理,執(zhí)?的流程如下圖所示:

1.4.1 實現(xiàn)原理源碼分析
所有的 Controller 執(zhí)?都會通過?個調(diào)度器 DispatcherServlet 來實現(xiàn),這?點可以從 Spring Boot 控制臺的打印信息看出,如下圖所示:

?所有?法都會執(zhí)? DispatcherServlet 中的 doDispatch 調(diào)度?法,doDispatch 源碼如下:
protected void doDispatch(HttpServletRequest request, HttpServletResponse
response) throws Exception {
HttpServletRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false;
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
try {
try {
ModelAndView mv = null;
Object dispatchException = null;
try {
processedRequest = this.checkMultipart(request);
multipartRequestParsed = processedRequest != request;
mappedHandler = this.getHandler(processedRequest);
if (mappedHandler == null) {
this.noHandlerFound(processedRequest, response);
return;
}
HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.g
etHandler());
String method = request.getMethod();
boolean isGet = HttpMethod.GET.matches(method);
if (isGet || HttpMethod.HEAD.matches(method)) {
long lastModified = ha.getLastModified(request, mapped
Handler.getHandler());
if ((new ServletWebRequest(request, response)).checkNo
tModified(lastModified) && isGet) {
return;
}
}
// 調(diào)?預(yù)處理【重點】
if (!mappedHandler.applyPreHandle(processedRequest, respon
se)) {
return;
}
// 執(zhí)? Controller 中的業(yè)務(wù)
mv = ha.handle(processedRequest, response, mappedHandler.g
etHandler());
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}
this.applyDefaultViewName(processedRequest, mv);
mappedHandler.applyPostHandle(processedRequest, response,
mv);
} catch (Exception var20) {
dispatchException = var20;
} catch (Throwable var21) {
dispatchException = new NestedServletException("Handler di
spatch failed", var21);
}
this.processDispatchResult(processedRequest, response, mappedH
andler, mv, (Exception)dispatchException);
} catch (Exception var22) {
this.triggerAfterCompletion(processedRequest, response, mapped
Handler, var22);
} catch (Throwable var23) {
this.triggerAfterCompletion(processedRequest, response, mapped
Handler, new NestedServletException("Handler processing failed", var23));
}
} finally {
if (asyncManager.isConcurrentHandlingStarted()) {
if (mappedHandler != null) {
mappedHandler.applyAfterConcurrentHandlingStarted(processe
dRequest, response);
}
} else if (multipartRequestParsed) {
this.cleanupMultipart(processedRequest);
}
}
}從上述源碼可以看出在開始執(zhí)? Controller 之前,會先調(diào)? 預(yù)處理?法 applyPreHandle,?applyPreHandle ?法的實現(xiàn)源碼如下:
boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
for(int i = 0; i < this.interceptorList.size(); this.interceptorIndex
= i++) {
// 獲取項?中使?的攔截器 HandlerInterceptor
HandlerInterceptor interceptor = (HandlerInterceptor)this.intercep
torList.get(i);
if (!interceptor.preHandle(request, response, this.handler)) {
this.triggerAfterCompletion(request, response, (Exception)null
);
return false;
}
}
return true;
}
從上述源碼可以看出,在 applyPreHandle 中會獲取所有的攔截器 HandlerInterceptor 并執(zhí)?攔截器中的 preHandle ?法,這樣就會咱們前?定義的攔截器對應(yīng)上了,如下圖所示:

此時?戶登錄權(quán)限的驗證?法就會執(zhí)?,這就是攔截器的實現(xiàn)原理。
1.4.2 攔截器小結(jié)
通過上?的源碼分析,我們可以看出,Spring 中的攔截器也是通過動態(tài)代理和環(huán)繞通知的思想實現(xiàn)的,?體的調(diào)?流程如下:

1.5 擴展:統(tǒng)一訪問前綴添加
所有請求地址添加 api 前綴:
@Configuration
public class AppConfig implements WebMvcConfigurer {
// 所有的接?添加 api 前綴
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.addPathPrefix("api", c -> true);
}
}
其中第?個參數(shù)是?個表達(dá)式,設(shè)置為 true 表示啟動前綴。
二、統(tǒng)一異常處理
統(tǒng)?異常處理使?的是 @ControllerAdvice + @ExceptionHandler 來實現(xiàn)的,@ControllerAdvice 表示控制器通知類,@ExceptionHandler 是異常處理器,兩個結(jié)合表示當(dāng)出現(xiàn)異常的時候執(zhí)?某個通知,也就是執(zhí)?某個?法事件,具體實現(xiàn)代碼如下:
package com.example.demo.config;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
/**
* 統(tǒng)一處理異常
*/
@ControllerAdvice
public class ErrorAdive {
@ExceptionHandler(Exception.class)
@ResponseBody
public HashMap<String, Object> exceptionAdvie(Exception e) {
HashMap<String, Object> result = new HashMap<>();
result.put("code", "-1");
result.put("msg", e.getMessage());
return result;
}
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public HashMap<String, Object> arithmeticAdvie(ArithmeticException e) {
HashMap<String, Object> result = new HashMap<>();
result.put("code", "-2");
result.put("msg", e.getMessage());
return result;
}
}
方法名和返回值可以?定義,重要的是 @ControllerAdvice 和 @ExceptionHandler 注解。
以上?法表示,如果出現(xiàn)了異常就返回給前端?個 HashMap 的對象,其中包含的字段如代碼中定義的那樣。
我們可以針對不同的異常,返回不同的結(jié)果,?以下代碼所示:
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {
@ExceptionHandler(Exception.class)
public Object exceptionAdvice(Exception e) {
HashMap<String, Object> result = new HashMap<>();
result.put("success", -1);
result.put("message", "總的異常信息:" + e.getMessage());
result.put("data", null);
return result;
}
@ExceptionHandler(NullPointerException.class)
public Object nullPointerexceptionAdvice(NullPointerException e) {
HashMap<String, Object> result = new HashMap<>();
result.put("success", -1);
result.put("message", "空指針異常:" + e.getMessage());
result.put("data", null);
return result;
}
}當(dāng)有多個異常通知時,匹配順序為當(dāng)前類及其子類向上依次匹配,案例演示:
在 UserController 中設(shè)置?個空指針異常,實現(xiàn)代碼如下:
@RestController
@RequestMapping("/u")
public class UserController {
@RequestMapping("/index")
public String index() {
Object obj = null;
int i = obj.hashCode();
return "Hello,User Index.";
}
}
以上程序的執(zhí)?結(jié)果如下:

此時若出現(xiàn)異常就不會報錯了,代碼會繼續(xù)執(zhí)行,但是會把自定義的異常信息返回給前端!
統(tǒng)一完數(shù)據(jù)返回格式后:
package com.example.demo.common;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 異常類的統(tǒng)一處理
*/
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {
@ExceptionHandler(Exception.class)
public Object exceptionAdvice(Exception e) {
return AjaxResult.fail(-1, e.getMessage());
}
}
統(tǒng)一異常處理不用配置路徑,是攔截整個項目中的所有異常。
三、統(tǒng)一數(shù)據(jù)返回格式
3.1 為什么需要統(tǒng)一數(shù)據(jù)返回格式
統(tǒng)?數(shù)據(jù)返回格式的優(yōu)點有很多,比如以下幾個:
- ?便前端程序員更好的接收和解析后端數(shù)據(jù)接?返回的數(shù)據(jù)。
- 降低前端程序員和后端程序員的溝通成本,按照某個格式實現(xiàn)就?了,因為所有接?都是這樣返回的。
- 有利于項?統(tǒng)?數(shù)據(jù)的維護(hù)和修改。
- 有利于后端技術(shù)部?的統(tǒng)?規(guī)范的標(biāo)準(zhǔn)制定,不會出現(xiàn)稀奇古怪的返回內(nèi)容。
3.2 統(tǒng)一數(shù)據(jù)返回格式的實現(xiàn)
統(tǒng)?的數(shù)據(jù)返回格式可以使用 @ControllerAdvice + ResponseBodyAdvice接口 的方式實現(xiàn),具體實現(xiàn)代碼如下:
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyA
dvice;
import java.util.HashMap;
/**
* 統(tǒng)一返回數(shù)據(jù)的處理
*/
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
/**
* 內(nèi)容是否需要重寫(通過此?法可以選擇性部分控制器和?法進(jìn)?重寫)
* 返回 true 表示重寫
*/
@Override
public boolean supports(MethodParameter returnType, Class converterTyp
e) {
return true;
}
/**
* ?法返回之前調(diào)?此?法
*/
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType,
MediaType selectedContentType,
Class selectedConverterType, ServerHttpR
equest request,
ServerHttpResponse response) {
// 構(gòu)造統(tǒng)?返回對象
HashMap<String, Object> result = new HashMap<>();
result.put("state", 1);
result.put("msg", "");
result.put("data", body);
return result;
}
}
統(tǒng)一處理后,此時所有返回的都是 json 格式的數(shù)據(jù)了。
若方法的返回類型為 String,統(tǒng)一數(shù)據(jù)返回格式封裝后,返回會報錯???
轉(zhuǎn)換器的問題,解決方案:

實際開發(fā)中這種統(tǒng)一數(shù)據(jù)返回格式的方式并不常用。因為它會將所有返回都再次進(jìn)行封裝,過于霸道了 ~
而通常我們會寫一個統(tǒng)一封裝的類,讓程序猿在返回時統(tǒng)一返回這個類 (軟性約束),例如:
package com.example.demo.common;
import java.util.HashMap;
/**
* 自定義的統(tǒng)一返回對象
*/
public class AjaxResult {
/**
* 業(yè)務(wù)執(zhí)行成功時進(jìn)行返回的方法
*
* @param data
* @return
*/
public static HashMap<String, Object> success(Object data) {
HashMap<String, Object> result = new HashMap<>();
result.put("code", 200);
result.put("msg", "");
result.put("data", data);
return result;
}
/**
* 業(yè)務(wù)執(zhí)行成功時進(jìn)行返回的方法
*
* @param data
* @return
*/
public static HashMap<String, Object> success(String msg, Object data) {
HashMap<String, Object> result = new HashMap<>();
result.put("code", 200);
result.put("msg", msg);
result.put("data", data);
return result;
}
/**
* 業(yè)務(wù)執(zhí)行失敗返回的數(shù)據(jù)格式
*
* @param code
* @param msg
* @return
*/
public static HashMap<String, Object> fail(int code, String msg) {
HashMap<String, Object> result = new HashMap<>();
result.put("code", code);
result.put("msg", msg);
result.put("data", "");
return result;
}
/**
* 業(yè)務(wù)執(zhí)行失敗返回的數(shù)據(jù)格式
*
* @param code
* @param msg
* @return
*/
public static HashMap<String, Object> fail(int code, String msg, Object data) {
HashMap<String, Object> result = new HashMap<>();
result.put("code", code);
result.put("msg", msg);
result.put("data", data);
return result;
}
}
同時搭配統(tǒng)一數(shù)據(jù)返回格式:
package com.example.demo.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import java.util.HashMap;
/**
* 統(tǒng)一數(shù)據(jù)返回封裝
*/
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@SneakyThrows
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if (body instanceof HashMap) { // 本身已經(jīng)是封裝好的對象
return body;
}
if (body instanceof String) { // 返回類型是 String(特殊)
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(AjaxResult.success(body));
}
return AjaxResult.success(body);
}
}
3.3 @ControllerAdvice 源碼分析(了解)
通過對 @ControllerAdvice 源碼的分析我們可以知道上?統(tǒng)?異常和統(tǒng)?數(shù)據(jù)返回的執(zhí)?流程,我們先從 @ControllerAdvice 的源碼看起,點擊 @ControllerAdvice 實現(xiàn)源碼如下:

從上述源碼可以看出 @ControllerAdvice 派?于 @Component 組件,?所有組件初始化都會調(diào)用 InitializingBean 接?。
所以接下來我們來看 InitializingBean 有哪些實現(xiàn)類?在查詢的過程中我們發(fā)現(xiàn)了,其中 Spring MVC中的實現(xiàn)?類是 RequestMappingHandlerAdapter,它??有?個?法 afterPropertiesSet() ?法,表示所有的參數(shù)設(shè)置完成之后執(zhí)?的?法,如下圖所示:

?這個?法中有?個 initControllerAdviceCache ?法,查詢此?法的源碼如下:

我們發(fā)現(xiàn)這個?法在執(zhí)?是會查找使?所有的 @ControllerAdvice 類,這些類會被容器中,但發(fā)?某個事件時,調(diào)?相應(yīng)的 Advice ?法,?如返回數(shù)據(jù)前調(diào)?統(tǒng)?數(shù)據(jù)封裝,?如發(fā)?異常是調(diào)?異常的 Advice ?法實現(xiàn)。
以上就是詳解SpringBoot中的統(tǒng)一功能處理的實現(xiàn)的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot統(tǒng)一功能處理的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
淺談如何優(yōu)雅地停止Spring Boot應(yīng)用
這篇文章主要介紹了淺談如何優(yōu)雅地停止Spring Boot應(yīng)用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
springboot后端存儲富文本內(nèi)容的思路與步驟(含圖片內(nèi)容)
在所有的編輯器中,大概最受歡迎的就是富文本編輯器和MarkDown編輯器了,下面這篇文章主要給大家介紹了關(guān)于springboot后端存儲富文本內(nèi)容的思路與步驟的相關(guān)資料,需要的朋友可以參考下2023-04-04
SpringBoot+MyBatis實現(xiàn)MD5加密數(shù)據(jù)庫用戶密碼的方法
MD5技術(shù)主要用于對用戶密碼加密,增加賬戶的安全性,他具有不可逆的特性,不會被輕易解密,這篇文章給大家介紹SpringBoot+MyBatis實現(xiàn)MD5加密數(shù)據(jù)庫用戶密碼的方法,感興趣的朋友跟隨小編一起看看吧2024-03-03
idea創(chuàng)建maven項目速度慢的三種解決方案
這篇文章主要介紹了idea創(chuàng)建maven項目速度慢的三種解決方案,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
如何在Spring Boot中實現(xiàn)異步處理與并發(fā)控制
本文我們將深入探討如何在Spring Boot中實現(xiàn)異步處理與并發(fā)控制,這一過程涉及到異步任務(wù)的執(zhí)行、線程池的配置、以及并發(fā)控制的實踐,以幫助我們提升應(yīng)用的性能和響應(yīng)能力,感興趣的朋友跟隨小編一起看看吧2024-07-07
淺談spring-boot 允許接口跨域并實現(xiàn)攔截(CORS)
本篇文章主要介紹了淺談spring-boot 允許接口跨域并實現(xiàn)攔截(CORS),具有一定的參考價值,有興趣的可以了解一下2017-08-08

