JSR303 数据校验
SpringBoot中可以用@validated 来校验数据
- 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
- 验证
JSR303 自定义注解校验
- 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
- 编写自定义注解
@Target(FIELD)
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {IsMobileValidator.class }) //使用哪一个校验器
public @interface IsMobile {
boolean required() default true;
String message() default "手机号码格式错误";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
一个自定义校验注解必须满足规范,在JSR303 规范中校验注解必须满足三个属性
String message() default "手机号码格式错误"; //校验出错误信息去哪里取 默认使用JSR303的ValidationMessages.properties 文件中取
Class<?>[] groups() default { }; //支持分组校验功能
Class<? extends Payload>[] payload() default { }; //一些负载信息
- 编写校验器类
实现 ConstraintValidator<T1,T2> 接口 声明两个泛型,第一个泛型:校验注解,第二个泛型:校验的字段类型,并实现初始化方法和判断校验是否成功方法
public class IsMobileValidator implements ConstraintValidator<IsMobile,String> {
private boolean required=true; //手机号码Value的值必填,默认必填
@Override
public void initialize(IsMobile constraintAnnotation) {
required = constraintAnnotation.required();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if(required){
return ValidatorUtils.isMobile(value);
}else{
if(StringUtils.isEmpty(value)){
return true;
}else{
return ValidatorUtils.isMobile(value);
}
}
}
}
多环境切换
springboot默认使用application.properties主配置文件
yaml的多文档模块
配置文件加载位置
springboot启动后会扫描application.properties 或者application.yml文件作为springboot的默认配置文件
配置文件优先级:
- 项目路径下的config文件夹配置文件
- 项目路径下的配置文件
- 资源路径下的config文件夹配置文件
- 资源路径下的配置文件
优先级由高到低,高优先级的配置会覆盖低优先级的配置,springboot会从者四个位置全部加载主配置文件,互补配置