Java 8 Optional<?> validation unwrapper in Spring -
in spring boot project when using following validation rules in dto
@length(max = 70) @unwrapvalidatedvalue private optional<string> vendorname;
i getting following exception
javax.validation.validationexception: hv000182: no validation value unwrapper registered type java.util.optional<java.lang.string>
i can't find anywhere how register custom validation value unwrapper in spring
you should register validatedvalueunwrapper
validator.
the validator configured via localvalidatorfactorybean
:
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemalocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"> <bean name="validator" class="org.springframework.validation.beanvalidation.localvalidatorfactorybean"> <property name="validationpropertymap"> <util:map> <entry key="hibernate.validator.validated_value_handlers" value="com.mycompany.validator.optionalvalidatedvalueunwrapper"/> </util:map> </property> </bean> </beans>
or in java:
@bean public localvalidatorfactorybean validator() { localvalidatorfactorybean validator = new localvalidatorfactorybean(); validator.getvalidationpropertymap().put("hibernate.validator.validated_value_handlers", "com.mycompany.validator.optionalvalidatedvalueunwrapper"); return validator; }
you find proper validatedvalueunwrapper
implementation in dropwizard framework (based on optional
guava).
public class optionalvalidatedvalueunwrapper extends validatedvalueunwrapper<optional<?>> { private final typeresolver resolver = new typeresolver(); @override public object handlevalidatedvalue(final optional<?> optional) { return optional.ornull(); } @override public type getvalidatedvaluetype(final type type) { resolvedtype resolvedtype = resolver.resolve(type); return resolvedtype.typeparametersfor(optional.class).get(0).geterasedtype(); } }
Comments
Post a Comment