Spring validation with @valid where / as custom error messages

I am trying to do a spring check with error messages in property files. But the examples I find, everything seems to have hardcoded values ​​or retrieved from the properties file, but using the validator class and extracting it there.

My setup is a little different. I use @Valid annotation in my requestmapping, and my @Valid class uses @NotNull, etc. I saw some examples when people do @NotNull (message = "blablabla"); But it is also hardcoded, and I would like to put the messages in the properties file so that I can easily edit it on the fly, and therefore I can easily implement i18n in the future.

Any contribution to this will be appreciated.

+3
source share
1 answer

It works in the same way as with an explicit one Validator- you declareMessageSource and write error messages in files .properties. Message codes are generated as constraintName.modelAttributeName.propertyName:

publib class Foo {
    @NotNull private String name;
    ...
}

.

@RequestMapping
public String submitFoo(@Valid Foo foo, ...) { ... }

messages.properties:

NotNull.foo.name=...

MessageSource Announcement:

<bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value = "messages" />
</bean>
+8
source

Source: https://habr.com/ru/post/1776975/


All Articles