003-maven to develop Java technology-point instructions scaffolding archrtype-

I. Overview

Second, the technical point instructions

2.1, springboot integration with mybatisplus

  [Code generator, paging, tombstone] Referring  Code

2.2, log4j2 integration

  See  Code

2.3, unified unified response [Exception]

1, a unified response to the output class BaseResponse

Package com.aaa.test.response; 

Import com.aaa.test.enums.ErrorCodeEnum; 

/ ** 
 * returns the result unified 
 * / 
public  class BaseResponse <T> {
     / ** 
     * returns Data 
     * * / 
    Private T Data; 

    / ** 
     * error code 
     * * / 
    Private Integer errorCode; 

    / ** 
     * error Messages 
     * * / 
    Private String errorMsg; 

    / ** 
     * successful 
     * * / 
    Private  boolean success = false ; 

    / **  
     * constructor unusual appearance
     ** / 
    Public BaseResponse (ErrorCodeEnum errorCodeEnum) {
         the this .errorCode = errorCodeEnum.getErrorCode ();
         the this .errorMsg = errorCodeEnum.getErrorMsg (); 
    } 

    / ** 
     * returns successfully Results 
     * * / 
    public BaseResponse (T Data) { 
        Success = to true ;
         the this .data = Data; 
    } 

    / ** 
     * returns successfully results 
     * * / 
    public BaseResponse ( Boolean success, ErrorCodeEnum errorCodeEnum, T Data) {
         the this .success = success;
        this.data = data;
        this.errorCode = errorCodeEnum.getErrorCode();
        this.errorMsg = errorCodeEnum.getErrorMsg();
    }

    public static <T> BaseResponse success(T data) {
        return new BaseResponse(data);
    }
    public static <T> BaseResponse success(ErrorCodeEnum errorCodeEnum) {
        return new BaseResponse(true,errorCodeEnum,null);
    }

    public static BaseResponse fail(ErrorCodeEnum errorCodeEnum) {
        return new BaseResponse(errorCodeEnum);
    }


    public static BaseResponse fail() {
        return new BaseResponse(ErrorCodeEnum.result_exception);
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Integer getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(Integer errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    @Override
    public String toString() {
        return "BaseResponse{" +
                "data=" + data +
                ", errorCode='" + errorCode + '\'' +
                ", errorMsg='" + errorMsg + '\'' +
                ", success=" + success +
                '}';
    }
}
View Code

 

Which uses the error code ErrorCodeEnum

Package com.aaa.test.enums; 

/ ** 
 * Error Codes enumeration class 
 * / 
public  enum ErrorCodeEnum {
     // success response class 
    success (200000, "successful" ), 
    no_response_data ( 200001, "there is no return data" ), 

    / / request class response code 
    Param_does_not_exist (400001, "lookup parameter does not exist" ), 
    Param_does_not_correct ( 400002, "was passed in an incorrect format" ), 
    HttpMediaTypeNotSupportedException ( 400003, "unsupported Content-type type" ), 

    result_exception ( 600000, "pending exception server" ), 

    ; 

    ErrorCodeEnum (errorCode Integer, String errorMsg) { 
        the this .errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    /**
     * 错误码
     */
    private Integer errorCode;

    /**
     * 错误信息
     */
    private String errorMsg;

    public Integer getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(Integer errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }
}
View Code

 

Technical requirements

  1, class unified response to support the success or failure of static methods

  2, error code, should be designed to six numeric type, where 200,000 successful category type, request type code 400,000, 500,000 for the server abnormal, greater than 600,000 yards to other customer-defined code, 

2, Controller write

  Controller supports a variety of response parameters

    Common type String, int, Integer, Map, Object, a single class, etc.

    Support the use of the above: BaseResponse response class Packaging

    Support the use of: ResponseEntity type of reception

  Through a unified response processing returns to unity: BaseResponse format

3, unified response to treatment program 

  Write RestControllerAdvice, response, and exception handling unity

/ ** 
 * returns the result unified exception class 
 * / 
@RestControllerAdvice 
public  class ResponseResultBodyAdvice the implements ResponseBodyAdvice <Object> {
     Private  Final Logger LoggerFactory.getLogger = log (ResponseResultBodyAdvice. Class );
     Private  static  Final Class <? The extends ANNOTATION_TYPE = responseBody the Annotation>. class ; 

    / ** 
     * is determined whether the class or method @ResponseResultBody 
     * / 
    @Override 
    public  Boolean the Supports (MethodParameter the returnType, class <? the extends HttpMessageConverter types <>>?converterType) {
         return AnnotatedElementUtils.hasAnnotation (returnType.getContainingClass (), ANNOTATION_TYPE) || returnType.hasMethodAnnotation (ANNOTATION_TYPE); 
    } 

    / ** 
     * When a class or method This method is called @ResponseResultBody 
     * / 
    @Override 
    public Object beforeBodyWrite (Object body, the returnType MethodParameter, the MediaType selectedContentType, Class <? the extends HttpMessageConverter types <>>? selectedConverterType, ServerHTTPRequest Request, Response ServerHttpResponse) {
         // avoid multiple conversions have returned to base-type 
        IF (body the instanceof BaseResponse) {
             return body; 
        }
        return BaseResponse.success(body);
    }

    /**
     * 提供对标准Spring MVC异常的处理
     *
     * @param ex      the target exception
     * @param request the current request
     */
    @ExceptionHandler(Exception.class)
    public final ResponseEntity<BaseResponse<?>> exceptionHandler(Exception ex, WebRequest request) {
        log.error("ExceptionHandler: {}", ex.getMessage());
        HttpHeaders headers = new HttpHeaders();
        if (ex instanceofHttpMediaTypeNotSupportedException) {
             // for client needs to return a String Content-type set of file application / JSON 
            return  the this .handleResultException ( new new ResultException (ErrorCodeEnum.HttpMediaTypeNotSupportedException), 
                    headers, Request); 
        } the else  IF (EX the instanceof ResultException) {
             return  the this . handleResultException ((ResultException) EX, headers, Request); 
        } 
        // the TODO: where other exceptions can customize interception 
        return  the this .handleException (EX, headers, Request); 
    } 

    / ** 
     * returns the processing to return the result of class ResultException
     */
    protected ResponseEntity<BaseResponse<?>> handleResultException(ResultException ex, HttpHeaders headers, WebRequest request) {
        BaseResponse<?> body = BaseResponse.fail((ex.getErrorCodeEnum()));
        HttpStatus status = null;
        if (ex.getErrorCodeEnum().getErrorCode().intValue() >= 500000) {
            status = HttpStatus.INTERNAL_SERVER_ERROR;
        } else if (ex.getErrorCodeEnum().getErrorCode().intValue() >= 400000) {
            status = HttpStatus.BAD_REQUEST;
        }
        return this.handleExceptionInternal(ex, body, headers, status, request);
    }

    /**
     * 异常类的统一处理
     */
    protected ResponseEntity<BaseResponse<?>> handleException(Exception ex, HttpHeaders headers, WebRequest request) {
        BaseResponse<?> body = BaseResponse.fail();
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        return this.handleExceptionInternal(ex, body, headers, status, request);
    }

    /**
     * org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
     * handleExceptionInternal(java.lang.Exception, java.lang.Object, org.springframework.http.HttpHeaders,
     * org.springframework.http.HttpStatus, org.springframework.web.context.request.WebRequest)
     * <p>
     * A single place to customize the response body of all exception types.
     * <p>The default implementation sets the {@link WebUtils#ERROR_EXCEPTION_ATTRIBUTE}
     * request attribute and creates a {@link ResponseEntity} from the given
     * body, headers, and status.
     */
    protected ResponseEntity<BaseResponse<?>> handleExceptionInternal(
            Exception ex, BaseResponse<?> body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
            request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, ex, WebRequest.SCOPE_REQUEST);
        }
        return new ResponseEntity<>(body, headers, status);
    }
}
View Code

 

  In the above-described return a String, and the other type of Object, or empty type conversion exception occurs. Do the following process:

  1, the configuration WebMvcConfigurer, will MappingJackson2HttpMessageConverter

/ Old version WebMvcConfigurerAdapter spring5 abandoned WebMvcConfigurerAdapter 
@Configuration 
public  class WebMvcConfig   the implements WebMvcConfigurer { 
    @Override 
    public  void configureMessageConverters (List <HttpMessageConverter <? >> Converters) {
         // mention the front, mainly in order to deal with the underlying type when not cast String XXX similar problems type, request type must be combined file application / JSON
         // advance using MappingJackson2HttpMessageConverter treatment process to avoid the use of type String StringHttpMessageConverter 
        converters.add (0, new new MappingJackson2HttpMessageConverter ()); 
    } 
}
View Code

 

    Main functions: // mention the front, the main basis for dealing with the type XXX not cast String type similar problems, combined with a request type must be application / json

        // advance using MappingJackson2HttpMessageConverter treatment to avoid using StringHttpMessageConverter treatment of type String

  2, write controller level aop, a major role in treatment, the object is null, and String is null, type conversion when converting BaseResponse abnormal

/ ** 
 * unified result processing section, null when processing returns note 
 * / 
@Aspect 
@Component 
public  class ResponseAspect { 
    @Around ( "Execution (com.aaa.test.controller .. * * (..))" )
     public controllerProcess Object (ProceedingJoinPoint PJD) throws the Throwable { 
        Object Result = pjd.proceed ();
         // be null special handling 
        IF (Result == null ) {
             the try { 
                MethodSignature Signature = (MethodSignature) pjd.getSignature (); 
                Class the returnType =signature.getReturnType ();
                 IF ( "java.lang.Object" .equals (returnType.getName ())) {
                     // Object this way 
                    return BaseResponse.success (Result); 
                } the else  IF ( "java.lang.String " .equals (returnType.getName ())) {
                     // initialization string returns a new 
                    return returnType.newInstance (); 
                } 
                // else return default 
                return Result; 
            } the catch (Exception EX) { 
                ex.printStackTrace (); 
            } 
        } 
        return Result; 
    }
}
View Code

 

Guess you like

Origin www.cnblogs.com/bjlhx/p/11780672.html