SpringBoot RESTful API返回统一数据格式还不懂?

fanix 2020-04-09

关于 Spring 的全局处理,有两方面要说:

统一数据返回格式
统一异常处理
为了将两个问题说明清楚,将分两个章节分别说明,本章主要说第一点
有童鞋说,我们项目都做了这种处理,就是在每个 API 都单独工具类将返回值进行封装,但这种不够优雅;我想写最少的代码完成这件事,也许有童鞋说,加几个注解就解决问题了,说的没错,但这篇文章主要是为了说明为什么加了几个注解就解决问题了,目的是希望大家知其所以然。

为了更好的说明问题,本文先说明如何实现,然后再详细剖析实现原理(这很关键)

为什么要做统一数据返回格式

前后端分离是当今服务形式的主流,如何让前端小伙伴可以处理标准的 response JSON 数据结构都至关重要,为了让前端有更好的逻辑展示与页面交互处理,每一次 RESTful 请求都应该包含以下几个信息:

名称

描述

status

状态码,标识请求成功与否,如 [1:成功;-1:失败]

errorCode

错误码,给出明确错误码,更好的应对业务异常;请求成功该值可为空

errorMsg

错误消息,与错误码相对应,更具体的描述异常信息

resultBody

返回结果,通常是 Bean 对象对应的 JSON 数据, 通常为了应对不同返回值类型,将其声明为泛型类型 实现

通用返回值类定义

根据上面的描述,用 Java Bean 来体现这个结构就是这样:

@Data

public final class CommonResult<T> {

private int status = 1;

private String errorCode = "";

private String errorMsg = "";

private T resultBody;

public CommonResult() {

}

public CommonResult(T resultBody) {

SpringBoot RESTful API返回统一数据格式还不懂?
SpringBoot RESTful API返回统一数据格式还不懂?

}

}

配置

没错,我们需要借助几个关键注

@EnableWebMvc

@Configuration

public class UnifiedReturnConfig {

@RestControllerAdvice("com.example.unifiedreturn.api")

static class CommonResultResponseAdvice implements ResponseBodyAdvice<Object>{

@Override

public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {

return true;

}

@Override

public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

if (body instanceof CommonResult){

return body;

}

return new CommonResult<Object>(body);

}

}

}

dy);

}

}

}

到这里就结束了,我们就可以纵情的写任何 RESTful API 了,所有的返回值都会有统一的 JSON

@RestController

@RequestMapping("/users")

public class UserController {

@GetMapping("")

public List<UserVo> getUserList(){

List<UserVo> userVoList = Lists.newArrayListWithCapacity(2);

userVoList.add(UserVo.builder().id(1L).name("一米八的一小伙").age(18).build());

userVoList.add(UserVo.builder().id(2L).name("tan").age(19).build());

return userVoList;

}

}

lder().id(2L).name("tan").age(19).build());

return userVoList;

}

}

}

@GetMapping("/{id}")

public UserVo getUserByName(@PathVariable Long id){

return UserVo.builder().id(1L).name("一米八的一小伙").age(18)

getUserByName(@PathVariable Long id){

return UserVo.builder().id(1L).name("一米八的一小伙").age(18).

e("一米八的一小伙").age(18).

@GetMapping("/testResponseEntity")

public ResponseEntity getUserByAge(){

return new ResponseEntity(UserVo.builder().id(1L).name("一米八的一小伙").age(18).build(), H

ty getUserByAge(){

return new ResponseEntity(UserVo.builder().id(1L).name("一米八的一小伙").age(18).build(), HttpStatus.OK);

}

d(), HttpStatus.OK);

}

打开浏览器输入地址测试: http://localhost:8080/users/testR

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.TYPE)

@Documented

@Import(DelegatingWebMvcConfiguration.class)

public

icy.RUNTIME)

@Target(ElementType.TYP

ME)

@Target(ElementType.TYPE)

@Doc

TYPE)

@Doc

@Configuration

public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

...

}

引入了 DelegatingWebMvcConfiguration.class,那来看这个类吧:

@Configurat

@Bean

public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {

RequestMappingHandlerAdapter adapter = createRequestMappingHandlerAdapter();

...

return adapter;

}

lic RequestMappingHandlerAdapte

public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter

implements BeanFactoryAware, InitializingBean {

...

}

RequestMappingHandlerAdapter 是每一次请求处理的关键,来看该类的定义:

public class RequestMappingHandlerAdapter extends AbstractHandle

@Override

public void afterPropertiesSet() {

// Do this first, it may add ResponseBody advice beans

initControllerAdviceCache();

if (this.argumentResolvers == null) {

List<HandlerMethodArgumentResolver> resolvers = getDefaultArgumentResolvers();

this.argumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);

}

if (this.initBinderArgumentResolvers == null) {

List<HandlerMethodArgumentResolver> resolvers = getDefaultInitBinderArgumentResolvers();

this.initBinderArgumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);

}

if (this.returnValueHandlers == null) {

List<HandlerMethodReturnValueHandler> handlers = getDefaultReturnValueHandlers();

this.returnValueHandlers = new HandlerMethodReturnValueHandlerCompos

ull) {

L

andlers(handle

ull) {

L

}

ull) {

L

private void initControllerAdviceCache() {

...

if (logger.isInfoEnabled()) {

logger.info("Looking for @ControllerAdvice: " + getApplicationContext());

}

List<ControllerAdviceBean> beans = ControllerAdviceBean.findAnnotatedBeans(getApplicationContext());

AnnotationAwareOrderComparator.sort(beans);

List<Object> requestResponseBodyAdviceBeans = new ArrayList<Object>();

for (ControllerAdviceBean bean : beans) {

...

if (ResponseBodyAdvice.class.isAssignableFrom(bean.getBeanType())) {

requestRespon

(beans);

List<Object> requestRe

ns);

List<Object> requestResponseBodyAdviceBean

sponseBodyAdviceBean

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@Documented

@ControllerAdvice

@Response

stResponseBodyAdviceBeans.add(bean);

stResponseBodyAdviceBeans.add(bean);

}

}

ceBeans.add(bean);

}

}

}

}

}

通过 ControllerAdviceBean 静态方法扫描

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@Documented

@ControllerAdvice

@ResponseBo

@ControllerAdvice

@ResponseBody

public @interfa

eBody

public @interface RestControllerAd

ce RestControllerAd

if (messageConverter instanceof GenericHttpMessageConverter) {

if (((GenericHttpMessageConverter) messageConverter).canWrite(

declaredType, valueType, selectedMediaType)) {

outputValue = (T) getAdvice().beforeBodyWrite(outputValue, returnType, selectedMediaType,

(Class<? extends HttpMessageConverter<?>>) messageConverter.getClass(),

inputMessage, outputMessage);

...

return;

}

}

nericHttpMessageConve

pro

{

outputValue = (T) getAdvice().bef

{

outputValue = (T) getAdvice().beforeBodyWrite(outputValue, retur

) getAdvice().beforeBodyWrite(outputValue, retur

class RequestResponseBodyAdviceChain implements RequestBodyAdvice, ResponseBodyAdvice<Object> {

@Override

public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType contentType,

Class<? extends HttpMessageConverter<?>> converterType,

ServerHttpRequest request, ServerHttpResponse response) {

return processBody(body, returnType, contentType, converterType, request, response);

}

@SuppressWarnings("unchecked")

private <T> Object processBody(Object body, MethodParameter returnType, MediaType contentType,

Class<? extends HttpMessageConverter<?>> converterType,

ServerHttpRequest request, ServerHttpResponse response) {

for (ResponseBodyAdvice<?> advice : getMatchingAdvice(returnType, ResponseBodyAdvice.class)) {

if (advice.supports(returnType, converterType)) {

body = ((ResponseBodyAdvice<T>) advice).beforeBodyWrite((T) body, returnType,

e,

ServerHttpRequest request, ServerHttpResponse response) {

for (ResponseBodyAdvice<?> advice : getMatchingAdvice(returnType, ResponseBodyAdvice.class)) {

if (advice.supports(returnType, converterType)) {

body = ((ResponseBodyAdvice<T>) advice).beforeBodyWrite((T) body, returnType,

contentType, converterType, reques

body, returnType,

contentType, converterType, request, response);

}

}

re

verterType, request, response);

}

}

return body;

}

}

);

}

}

return body;

}

}

}

@Override

public void handleReturnValue(Object returnValue, MethodParameter returnType,

ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

HandlerMethodReturnValueHandler handler = selectHandler(returnValue, returnType);

if (handler == null) {

throw new IllegalArgumentException("Unknown return value type: " + returnType.g

Value, MethodParameter returnType,

ModelAndViewContainer mavContaine

meter returnType,

ModelAndViewContainer mavContainer, NativeWebRequest webRequest)

iner, NativeWebRequest webRequest) throws Exception {

t) throws Exception {

HandlerMethodReturnVal

HandlerMethodReturnVal

@Override

public boolean supportsParameter(MethodParameter parameter

;

}

handler.handleReturnValue(returnValue, retur

;

}

handler.handleReturnValue(retu

;

}

handler.handleReturnValue(returnValue, returnType, mavContainer, webRequ

ue(returnValue, returnType, mavContainer, webRequ

@Override

public void handleReturnValue(Object returnValue, MethodParameter returnType,

ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

...

if (responseEntity instanceof ResponseEntity) {

int returnStatus = ((ResponseEntity<?>) responseEntity).getStatusCodeValue();

outputMessage.getServletResponse().setStatus(returnStatus);

if (returnStatus == 200) {

if (SAFE_METHODS.contains(inputMessage.getMethod())

&& isResourceNotModified(inputMessage, outputMessage)) {

// Ensure headers are flushed, no body should be written.

outputMessage.flush();

// Skip call to converters, as they may update the body.

return;

}

}

}

// Try even with null body. ResponseBodyAdvice could get involved.

writeWithMessageConverters(responseEntity.getBody()

od())

&& isResourceNotModified(inputMessage, outputMessage)) {

// Ensure headers are flushed, no body should be written.

outputMessage.flush();

// Skip call to converters, as they may update the body.

return;

}

}

}

// Try even with null body. ResponseBodyAdvice could get involved.

writeWithMessageConverters(responseEntity.getBody(), returnType, inputMessage, outputMessage);

// Ens

ty.getBody(), returnType, inputMessage, outputMessage);

// Ensure headers are flushed even i

);

// Ensure headers are flushed even if no body was written.

outp

ed even if no body was written.

outputMessage.flush();

}

.

outputMessage.flush();

}

该方法提取出 responseEntity.getBody(),并传递个 MessageConverter,然后再继续调用 beforeBodyWrite 方法,这才是真相!!!

这是 RESTful API 正常返回内容的情况

相关推荐