Skip to content

Unwrap a validator instance of specified type contained in SpringValidatorAdapter #37119

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
*
* @author Stephane Nicoll
* @author Phillip Webb
* @author Zisis Pavloudis
* @since 2.0.0
*/
public class ValidatorAdapter implements SmartValidator, ApplicationContextAware, InitializingBean, DisposableBean {
Expand Down Expand Up @@ -153,4 +154,17 @@ private static Validator wrap(Validator validator, boolean existingBean) {
return validator;
}

@Override
@SuppressWarnings("unchecked")
public <T> T unwrap(Class<T> type) {
if (type.isAssignableFrom(this.target.getClass())) {
if (this.target instanceof SpringValidatorAdapter adapter) {
return adapter.unwrap(type);
}
return (T) this.target;
}

throw new IllegalArgumentException("Cannot unwrap " + this.target + " to " + type.getName());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@

import java.util.HashMap;

import jakarta.validation.Validator;
import jakarta.validation.constraints.Min;
import org.hibernate.validator.HibernateValidator;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import org.springframework.boot.test.context.FilteredClassLoader;
Expand Down Expand Up @@ -91,6 +94,15 @@ void wrapperWhenValidationProviderNotPresentShouldNotThrowException() {
.run((context) -> ValidatorAdapter.get(context, null));
}

@Test
void unwrapValidatorInstanceOfJakartaTypeAndExceptionThrownWhenTypeNotSupported() {
this.contextRunner.withUserConfiguration(LocalValidatorFactoryBeanConfig.class).run((context) -> {
ValidatorAdapter wrapper = context.getBean(ValidatorAdapter.class);
assertThat(wrapper.unwrap(Validator.class)).isInstanceOf(Validator.class);
Assertions.assertThrows(IllegalArgumentException.class, () -> wrapper.unwrap(HibernateValidator.class));
});
}

@Configuration(proxyBeanMethods = false)
static class LocalValidatorFactoryBeanConfig {

Expand Down