Springboot常用技巧

前后端时间格式转换

前端传递utc时间格式,前端展示规范时间格式,可以通过注解完成

DTO(接收前端时间时):
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")

VO(返回前端时间时):
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")

接口统一日志处理

利用aop统一拦截接口,输出日志

package com.crc.common.aop;

import com.crc.common.bean.BaseResBean;
import com.crc.common.define.CommonDefine;
import com.crc.common.utils.JWTTokenUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;

/**
 * 日志切面
 */
@Slf4j
@Component
@Aspect
public class LogAspect {

    @Pointcut("@within(org.springframework.web.bind.annotation.RestController) && execution(* com.crc.admin..controller..*.*(..))")
    public void pointCut() {
    }

    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint) throws JsonProcessingException {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        log.info("请求开始 {},url:{},---header:{}--- req:{}",
                getApiOperationStr(joinPoint),
                request.getRequestURI(),
                getHeader(request),
                getReq(request, joinPoint));
    }

    @AfterReturning(pointcut = "pointCut()", returning = "returnValue")
    public void releaseResource(BaseResBean returnValue) throws JsonProcessingException {
        log.info("请求结束res:{}", new ObjectMapper().writeValueAsString(returnValue));
    }

    private String getApiOperationStr(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        ApiOperation manageLogin = method.getAnnotation(ApiOperation.class);
        if (manageLogin == null) {
            return "";
        }
        return manageLogin.value();
    }

    private String getReq(HttpServletRequest request, JoinPoint joinPoint) throws JsonProcessingException {
        if ("GET".equals(request.getMethod())) {
            return new ObjectMapper().writeValueAsString(request.getParameterMap());
        }
        return Arrays.toString(joinPoint.getArgs());
    }

    private String getHeader(HttpServletRequest request) {
        String token = request.getHeader(CommonDefine.TOKEN_NAME);
        return String.format("{account:%s,token:%s}",JWTTokenUtil.getUseridByFullJWTToken(token),token);
    }
}

统一接口参数校验

加入spring容器管理即可生效

package com.crc.common.config;

import com.crc.common.bean.BaseResBean;
import com.crc.common.define.CrcErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常捕获
 */
@Slf4j
@RestControllerAdvice
public class CrcServerExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public BaseResBean resolveException(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        if (fieldError == null) {
            return CrcErrorCodeEnum.PARAM_IS_NULL.toReturnValue();
        }
        return CrcErrorCodeEnum.PARAM_IS_NULL.error(fieldError.getDefaultMessage());
    }

}

你可能感兴趣的:(springboot)