【问题标题】:javax.validation.Validator exclude some fieldsjavax.validation.Validator 排除一些字段
【发布时间】:2020-03-28 05:21:41
【问题描述】:

我有两个不同的服务:第一个是保存一个对象到数据库,第二个是更新现有的对象。

我正在为我的对象使用验证约束,例如(@NotBlank、@Size、@Pattern 等),在第一种情况下,我需要验证对象的所有字段,但在后一种情况下,某些字段需要被排除在验证器之外。

目前,我正在使用 javax.validation.Validator 进行验证。这是我的对象...

public class Person {

  private Long id;

  @NotBlank
  @Size(max = 45)
  private String name;

  @Size(max = 5000)
  private String description;

  @Size(max = 300)
  private String address;
}

...我想在更新验证期间排除“地址”字段。

@Named
@RequiredArgsConstructor
@Service
@Slf4j
public class PersonService {

private final PersonRepository repository;
private final Validator validator = buildDefaultValidatorFactory().getValidator();

public Person save(Person person) {
    Set<ConstraintViolation<Person>> violations = validator.validate(person);

    if (!violations.isEmpty()) {
      throw new ConstraintViolationException(new HashSet<>(violations));
    }

    return repository.save(person);
}

public Person update(Person person) {
    Set<ConstraintViolation<Person>> violations = validator.validate(person); //exclude address field here

    if (!violations.isEmpty()) {
      throw new ConstraintViolationException(new HashSet<>(violations));
    }

    return repository.save(person);
}
}

【问题讨论】:

标签: java spring spring-boot validation


【解决方案1】:

如果您需要排除地址属性,只需在验证之前将其设置为 null。并在验证后将其设置为之前的值:

public Person update(Person person) {
    String address = person.getAddress();
    person.setAddress(null);

    Set<ConstraintViolation<JobAd>> violations = validator.validate(person);

    if (!violations.isEmpty()) {
      throw new ConstraintViolationException(new HashSet<>(violations));
    }

    person.setAddress(address)
    return repository.save(person);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多