Skip to content

Commit

Permalink
Ensure validators accessible as beans from usingContext (#337)
Browse files Browse the repository at this point in the history
* Ensure validators accessible as beans from usingContext

The usingContext method of DefaultValidatoryFactory is updated to check
for an existing non-null ValidatorConfiguration that is itself an
instance of ValidatorContext (which will always be the case when
created via DI).

This allows custom validation constraints to be located in the
BeanContext when validation is invoked by a Jakarta validation
implementation.

* Code improvement for Sonar
  • Loading branch information
jeremyg484 authored Mar 28, 2024
1 parent 8ffe4a6 commit 3f95ed1
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,13 @@ public jakarta.validation.Validator getValidator() {

@Override
public ValidatorContext usingContext() {
DefaultValidatorConfiguration newValidatorConfiguration = new DefaultValidatorConfiguration();
newValidatorConfiguration.setBeanIntrospector(configuration.getBeanIntrospector());
return newValidatorConfiguration;
if (configuration instanceof ValidatorContext validatorContext) {
return validatorContext;
} else {
DefaultValidatorConfiguration newValidatorConfiguration = new DefaultValidatorConfiguration();
newValidatorConfiguration.setBeanIntrospector(configuration.getBeanIntrospector());
return newValidatorConfiguration;
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import io.micronaut.context.ApplicationContext
import io.micronaut.core.annotation.Introspected
import io.micronaut.validation.validator.Validator
import jakarta.validation.Valid
import jakarta.validation.ValidatorFactory
import spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification
Expand All @@ -15,6 +16,8 @@ class CustomConstraintsSpec extends Specification {
ApplicationContext applicationContext = ApplicationContext.run()
@Shared
Validator validator = applicationContext.getBean(Validator)
@Shared
ValidatorFactory validatorFactory = applicationContext.getBean(ValidatorFactory)

void "test validation where pojo with inner custom constraint fails"() {
given:
Expand Down Expand Up @@ -194,6 +197,19 @@ class CustomConstraintsSpec extends Specification {
then:
result == "AB"
}

void "test custom validator bean can be invoked when using jakarta validation ValidatorFactory.usingContext"() {
given:
TestInvalid testInvalid = new TestInvalid(invalidInner: new TestInvalid.InvalidInner())
Validator contextualValidator = validatorFactory.usingContext().getValidator() as Validator

when:
def violations = contextualValidator.validate(testInvalid)

then:
violations.size() == 1
violations[0].message == "invalid"
}
}

@Introspected
Expand Down

0 comments on commit 3f95ed1

Please sign in to comment.