An open API service indexing awesome lists of open source software.

https://github.com/cepr0/sb-constraint-validator-injection-demo

Demo of the custom ConstraintValidator as a Spring Bean
https://github.com/cepr0/sb-constraint-validator-injection-demo

bean constraint-validation injection spring spring-boot validation

Last synced: 28 days ago
JSON representation

Demo of the custom ConstraintValidator as a Spring Bean

Awesome Lists containing this project

README

          

## Demo of the custom ConstraintValidator as a Spring Bean

Spring Boot allows injecting Spring beans to a ConstraintValidator, for example:

```java
@Slf4j
public class CaseValidator implements ConstraintValidator {

private final Predicate uppercasePredicate;
private final Predicate lowercasePredicate;

private CheckCase.CaseMode caseMode;

@Autowired // not necessary annotation
public CaseValidator(Predicate uppercasePredicate, Predicate lowercasePredicate) {
this.uppercasePredicate = uppercasePredicate;
this.lowercasePredicate = lowercasePredicate;
}

@Override
public void initialize(CheckCase constraintAnnotation) {
this.caseMode = constraintAnnotation.value();
}

@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) return true;

if (caseMode == CheckCase.CaseMode.UPPER) {
log.info("[i] Checking uppercase for value: {}", value);
return uppercasePredicate.test(value);
} else {
log.info("[i] Checking lowercase for value: {}", value);
return lowercasePredicate.test(value);
}
}
}
```