关于springboot:springboot注解

46次阅读

共计 4610 个字符,预计需要花费 12 分钟才能阅读完成。

validation 注解

罕用注解

@Null  被正文的元素必须为 null
@NotNull  被正文的元素不能为 null,但能够为 empty, 没有 Size 的束缚
@AssertTrue  被正文的元素必须为 true
@AssertFalse  被正文的元素必须为 false
@Min(value)  被正文的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value)  被正文的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value)  被正文的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value)  被正文的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max,min)  被正文的元素的大小必须在指定的范畴内。@Digits(integer,fraction)  被正文的元素必须是一个数字,其值必须在可承受的范畴内
@Past  被正文的元素必须是一个过来的日期
@Future  被正文的元素必须是一个未来的日期
@Pattern(value) 被正文的元素必须合乎指定的正则表达式。@Email 被正文的元素必须是电子邮件地址
@Length 被正文的字符串的大小必须在指定的范畴内
@NotEmpty  被正文的字符串必须非空,不能为 null,且 Size>0
@Range  被正文的元素必须在适合的范畴内
@NotBlank  只用于 String, 不能为 null 且 trim()之后 size>0

应用 @Validated 验证。

应用 @RequestBody 验证 body 数据。

举例

  • UsersController
package com.chenglulu.controller.users;

import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping(value = "/", produces = {MediaType.APPLICATION_JSON_VALUE})
public class UsersController {@RequestMapping(value = "/register", method = RequestMethod.POST)
    public void registerUser(HttpServletRequest request, @Validated @RequestBody RegisterUsersParams params){}}
  • RegisterUsersParams
package com.chenglulu.controller.users.domain;

import com.chenglulu.constant.Validation;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

@Data
public class RegisterUsersParams {@NotBlank(message = "username is blank")
    private String username;
    
    @NotBlank(message = "phone is blank")
    @Pattern(regexp = Validation.PHONE)
    private String phone;
    
    @Email
    private String email;
}

全局异样解决

罕用注解

@ControllerAdvice
@ExceptionHandler  异样类型
@ResponseStatus  异样响应状态
@ResponseBody

举例

package com.chenglulu.exception;

import com.chenglulu.constant.Constants;
import com.chenglulu.constant.ErrorCode;
import com.chenglulu.controller.users.domain.BaseResponse;
import com.chenglulu.utils.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.support.RequestContextUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Locale;
@ControllerAdvice
public class GlobalExceptionHandler {
    @Autowired
 private MessageSource messageSource;
    
    /**
    * 未知异样解决 
    * @param request 申请
    * @param ex 异样对象
    */ 
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ResponseBody
 public HttpEntity<BaseResponse> handlerMethodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException ex){String requestId = getRequestIdHeader(request);
        
        String code = ErrorCode.PARAMETER_ERROR;
        Locale locale = RequestContextUtils.getLocale(request);
        BindingResult br = ex.getBindingResult();
        StringBuilder msgStr = new StringBuilder();
        List<FieldError> feList = br.getFieldErrors();
        for (FieldError fe : feList) {String message = fe.getDefaultMessage();
            String field = fe.getField();
            msgStr.append(field).append(message).append(";");
        }
        Object[] msgArg = new Object[]{msgStr};
        String message = messageSource.getMessage(code, msgArg, locale);
        BaseResponse res = ResponseUtil.error(requestId, code, message);
        return new HttpEntity<BaseResponse>(res);
    }
    
    /**
    * 未知异样解决 
    * @param request 申请
    * @param ex 异样对象
    */ 
    @ExceptionHandler(value = {Exception.class})
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
 public HttpEntity<BaseResponse> handlerException(HttpServletRequest request, Exception ex){String requestId = getRequestIdHeader(request);
        
        String code = ErrorCode.UNKNOWN_ERROR;
        BaseResponse res = ResponseUtil.error(request, requestId, code, null);
        return new HttpEntity<BaseResponse>(res);
    }
    
    private String getRequestIdHeader(HttpServletRequest request) {return request.getHeader(Constants.HEADER_X_REQUEST_ID);
    }
    
    private String getLocaleMessage(HttpServletRequest request) {}}

正文完
 0