标签:arraylist params mes att eval imp integer length add
说明:Validation 在Controller层使用Validation应该都使用过了,以下方式可以使用 Validation 在Service层完成对dto的属性校验,避免写一堆的 if else 来处理这些逻辑,提高开发效率,代码如下:
@Data
public class AddUserParamsDto implements Serializable {
private Integer id;
@NotEmpty(message = "用户名不能为空")
private String username;
@Length(min = 6, message = "密码长度不能小于6")
private String password;
@Max(value = 120, message = "年龄必须在18-120之间")
@Min(value = 18, message = "年龄必须在18-120之间")
private Integer age;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date birthday;
private String description;
}
@Configuration
public class ValidatorConfigBean {
@Bean
public ValidatorFactory validatorFactory() {
return Validation.byProvider(HibernateValidator.class)
.configure()
.failFast(false)
.buildValidatorFactory();
}
@Bean
public Validator validator(ValidatorFactory validatorFactory) {
return validatorFactory.getValidator();
}
}
@RestController
public class UserController {
@Resource
private UserService userService;
@GetMapping("/test/valid")
public Object validToService() {
AddUserParamsDto dto = new AddUserParamsDto();
dto.setUsername(null);
dto.setAge(200);
dto.setPassword("123");
return userService.validToService(dto);
}
}
@Service
public class UserServiceImpl implements UserService {
@Resource
private Validator validator;
@Override
public Object validToService(AddUserParamsDto dto) {
List<String> list = new ArrayList<>();
Set<ConstraintViolation<AddUserParamsDto>> violations = validator.validate(dto);
for (ConstraintViolation<AddUserParamsDto> violation : violations) {
list.add(violation.getMessage());
}
return list;
}
}
SpringBoot中在除Controller层 使用Validation的方式
标签:arraylist params mes att eval imp integer length add
原文地址:https://www.cnblogs.com/gxc6/p/11407599.html