手動呼叫hibernate的引數校驗器和springboot引數校驗器
阿新 • • 發佈:2020-11-01
package com.cmb.om;
import com.xx.xx.bean.dto.ApplyRcdSelectDtoX1;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;
/**
* @Title SelfCallValid
* @Package SelfCallValid
* @Description
* @Date 2020/6/8 15:51
* @Version 1.0
* @Copyright IT802482
*/
@RunWith (SpringRunner. class )
@SpringBootTest (classes = SpringBootApp. class )
public class SelfCallValid {
@Autowired
private Validator validator;
/**
* 手動呼叫hibernate校驗器
*/
@Test
public void test(){
XXXDto foo = new XXXDto();
ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
Validator validator = vf.getValidator();
Set<ConstraintViolation<XXXDto>> set = validator.validate(foo);
if (set.size()> 0 ){
System.out.println( "校驗不通過" );
} else {
System.out.println( "校驗通過" );
}
for (ConstraintViolation<XXXDto> constraintViolation : set) {
System.out.println( "原因:" +constraintViolation.getMessage());
}
}
/**
* 手動呼叫springboot封裝後的校驗器
*/
@Test
public void testSpringbootValid(){
XXXDto foo = new XXXDto();
Set<ConstraintViolation<XXXDto>> set = validator.validate(foo);
if (set.size()> 0 ){
System.out.println( "校驗不通過" );
} else {
System.out.println( "校驗通過" );
}
for (ConstraintViolation<XXXDto> constraintViolation : set) {
System.out.println( "原因:" +constraintViolation.getMessage());
}
}
}
|
dto:
1 2 3 4 5 |
@Data
public class XXXDto{
@NotBlank (message = "taskNo不允許為空" )
private String taskNo;
}
|