6.1 加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
6.2 在实体类上加注解
在实体类上加入@Validated注解。并且在属性上方加入@Emall(message="邮箱不符合要求"),则如果该属性不满足邮箱的格式,就会报错。
package jiang.com.helloworld.pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Email;
@Component
@ConfigurationProperties(prefix = "cat")
@Validated
public class Cat {
@Email(message = "邮箱地址不符合规范!")
private String catName;
private Integer catAge;
@Override
public String toString() {
return "Cat{" +
"catName='" + catName + '\'' +
", catAge=" + catAge +
'}';
}
public String getCatName() {
return catName;
}
public void setCatName(String catName) {
this.catName = catName;
}
public Integer getCatAge() {
return catAge;
}
public void setCatAge(Integer catAge) {
this.catAge = catAge;
}
public Cat(String catName, Integer catAge) {
this.catName = catName;
this.catAge = catAge;
}
public Cat() {
}
}
6.3 运行结果
如果属性不满足邮箱的格式:
如果属性满足邮箱的格式: