ValidationInformation resource: SpringBoot Docs: 2.8.9. @ConfigurationProperties Validation url: https://docs./spring-boot/docs/2.3.12.RELEASE/reference/html/spring-boot-features.html#boot-features Spring Boot attempts to validate @ConfigurationProperties classes whenever they are annotated with Spring’s @Validated annotation. You can use JSR-303 javax.validation constraint annotations directly on your configuration class. To do so, ensure that a compliant JSR-303 implementation is on your classpath and then add constraint annotations to your fields, as shown in the following example:
@ConfigurationProperties(prefix="acme") @Validated public class AcmeProperties { @NotNull private InetAddress remoteAddress; // ... getters and setters } You can also trigger validation by annotating the @Bean method that creates the configuration properties with @Validated.
To ensure that validation is always triggered for nested properties, even when no properties are found, the associated field must be annotated with @Valid. The following example builds on the preceding AcmeProperties example:
@ConfigurationProperties(prefix="acme") @Validated public class AcmeProperties { @NotNull private InetAddress remoteAddress; @Valid private final Security security = new Security(); // ... getters and setters public static class Security { @NotEmpty public String username; // ... getters and setters } } JSR-303 ValidationJSR-303 是Java EE的一個子規(guī)范,,官方參考實現(xiàn)Hibernate Validator JSR-303 是一個數(shù)據(jù)驗證的規(guī)范,,而Hibernate Validator則是實現(xiàn)了這一規(guī)范,,可以使用注解的方式對Bean進行驗證,它的內(nèi)部已經(jīng)定義好了一系列的限制注解,,只需將需要的注解標(biāo)注在需要驗證的實體類的屬性上或者是對應(yīng)的get方法上即可 JSR-303常用校驗規(guī)則布爾檢查
空值檢查
長度檢查
日期檢查
數(shù)值檢查
使用Hibernate Validator的Demo
org.hibernate.validatorhibernate-validator${hibernate-validator.version}
/** * @Email 約束輸入郵件的格式 * @NotBlank 指字符串使用trim()去掉前后空格后,,不能夠為空 */ @ToString @AllArgsConstructor @NoArgsConstructor @Data public class User implements Serializable { @NotBlank(message = "郵箱不能為空") @Email(message = "郵箱非法") private String userEmail; @NotBlank(message = "電話不能為空") @Pattern(regexp = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$",message = "手機號非法") private String userPhone; }
/** * 以POST請求為例 * @Validated 注釋類 * @RequestBody 可傳Javabean類型 * @RequestParam 傳單個參數(shù) * @Valid 修飾在Javabean類型前 */ @RestController @Validated public class UserController { @RequestMapping(value = "/test",method = RequestMethod.POST) public boolean test(@RequestBody @Valid User user){ return true; } @RequestMapping(value = "/hello",method = RequestMethod.GET) public String hello(){ return "hello,world"; } }
|
|
來自: 冒險的K > 《應(yīng)用文》