jsr-303校验
导入maven依赖。
<!--jsr303 校验-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
@Validated:开启数据校验功能
@AllArgsConstructor
@NoArgsConstructor
@Data
@Component // 注入到springboot
@Validated // 开启数据校验
@ConfigurationProperties(prefix = "dog") // 将yal配置文件中的数据注入
public class Dog {
@Email(message = "不是邮箱格式")
private String name;
private Integer age;
}
yml配置文件
dog:
name: "阿黄"
age: 10
测试
@SpringBootTest
class SpringProjectApplicationTests {
@Autowired // 自动装配
Dog dog;
@Test
void contextLoads() {
System.out.println(dog);
}
}
此时就会报异常因为不是邮件格式
Description:
Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'dog' to com.jing.pojo.Dog failed:
Property: dog.name
Value: 阿黄
Origin: class path resource [application.yml]:28:9
Reason: 不是邮箱格式