0

I have set up Spring Boot Validation Message for i18n with the various annotations and beans necessary and have it all working for example

SomePOJO

@NotEmpty(message = "{user.lastname_required}")
private String lastName;

messages.properties

user.lastname_required=Please provide your last name

My issues is if I have a typo in the properties file or the POJO or just miss adding an message, this will only be discovered at runtime when the error is thrown.

Has anyone come up with a solution for how to discover this during compilation?

1 Answer 1

0

It seems like that you excepted to load valid message dynamiclly .

you can add static constants which would define in a common constants class.

the code snippet is like following

step1. creat constants class


public class ValidationMessages {
    public static final String LAST_NAME_REQUIRED = "user.lastname_required";

}

// In your POJO
@NotEmpty(message = "{" + ValidationMessages.LAST_NAME_REQUIRED + "}")
private String lastName;

step 2. load message from application

you can use @Value annotation on setmethod that inject value into a static field

@Component
public class ValidationMessages {
    public static String LAST_NAME_REQUIRED = "user.lastname_required";


//  the message which behind ':' is  indicate default for the injection
    @Value("${user.lastname_required:last_name is required}")
    public void setLastname (String message) {
        LAST_NAME_REQUIRED = message;
    }

}

one more word , Define message in spring application.properties ,bind the validation message lifecycle scope with spring application that i think it is not the best practise in product environment. when ever you would like to change the message , if there is no hot refresh spring config in no shutdown model , it should refresh config via restart application , if it is frequently modified , it means that you would restart app in every modification.

The validation message should be a constants , not load from anywhere dynamiclly

2
  • Hi Peng, but I need these error message to be internationalized, so they need to be dynamic
    – iqueqiorio
    Commented Dec 16, 2023 at 5:06
  • fine , just follow the step ,that would get your expected message
    – Peng
    Commented Dec 18, 2023 at 1:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.