All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.taills.common.annotation.ApiResponseBodyAdvice Maven / Gradle / Ivy

package io.github.taills.common.annotation;

import io.github.taills.common.response.ApiResult;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.annotation.Annotation;

/**
 * @author taills
 * @date 2019/05/01
 */
@RestControllerAdvice
@ControllerAdvice(annotations = ApiResponseBody.class)
public class ApiResponseBodyAdvice implements ResponseBodyAdvice {

    private static final Class ANNOTATION_TYPE = ApiResponseBody.class;

    /**
     * 判断类或者方法是否使用了 @ResponseResultBody
     */
    @Override
    public boolean supports(MethodParameter returnType, Class> converterType) {
        return AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), ANNOTATION_TYPE) || returnType.hasMethodAnnotation(ANNOTATION_TYPE);
    }

    /**
     * 当类或者方法使用了 @ResponseResultBody 就会调用这个方法
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 防止重复包裹的问题出现
        if (body instanceof ApiResult) {
            return body;
        }
        return ApiResult.success(body);
    }
}