Spring Boot经验

发布时间 2023-04-28 17:39:38作者: ChenLiuyu

Spring、 Spring Boot经验

本文记录作者在实际使用Spring或则Spring Boot过程中遇到比较好的案例或则经验,以供开发学习使用

1. 校验篇

生产过程中前后端都会进行数据格式的校验,后端校验一般采用JSR303的校验模式

1.1 使用

引入依赖

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
</dependency>

1.2 简单校验

在相关实体类上增加校验注解

/**
 * 品牌id
 */
@NotNull(message = "修改必须指定品牌id", groups = {UpdateGroup.class})
@Null(message = "新增不能指定id", groups = {AddGroup.class})
@TableId
private Long brandId;

然后在实际需要校验的地方增加@Valid注解

public R update(@Validated(value = {UpdateGroup.class}) @RequestBody BrandEntity brand);

1.3 分组校验

@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Validated {

	/**
	 * Specify one or more validation groups to apply to the validation step
	 * kicked off by this annotation.
	 * <p>JSR-303 defines validation groups as custom annotations which an application declares
	 * for the sole purpose of using them as type-safe group arguments, as implemented in
	 * {@link org.springframework.validation.beanvalidation.SpringValidatorAdapter}.
	 * <p>Other {@link org.springframework.validation.SmartValidator} implementations may
	 * support class arguments in other ways as well.
	 */
	Class<?>[] value() default {};

}

在@Valid注解源码中可以看到value是个class的数组,可以进行分组作用
上文中有相关例子,在校验时如果使用分组校验,其他不匹配的分组校验或则不分组的校验将不生效。

自定义组

public interface UpdateGroup {
}

1.4 自定义异常

默认异常可以通过源码查看,也可以指定message
默认的返回值不一定符合系统设计时的结构,可以自定义全局异常来进行设置。