Spring boot yml ResourceBundle file
Asked Answered
R

2

14

I'm using MessageSource of Spring to load errors messages from a .properties file in classpath. My properties respect a certain "template" such as {Object}.{field}.{unrespectedConstraint} Example :

userRegistrationDto.password.Size= Le mot de passe doit avoir au minimum 6 caractères.
userRegistrationDto.email.ValidEmail= Merci de saisir une addresse mail valide.

In case of refactoring (Changing the name of the class for example), I have to change my properties file in several places.

Is there any way to use a yaml file (messages.yml) as a ResourceBundle to obtain something like :

userRegistrationDto:
  password:
    Size: Le mot de passe doit avoir au minimum 6 caractères.
  email:
    ValidEmail: Merci de saisir une addresse mail valide.
Retrospection answered 27/4, 2017 at 11:1 Comment(1)
Well, there's that (disclaimer: haven't tested it myself): github.com/akihyro/yaml-resource-bundleEndpaper
O
11

I think this should suffice for your requirements, if you need the MessageSource to be reloadable during VM operation, you might have to do a bit more digging.

@Configuration
public class TestConfig {

    @Bean(name = "testProperties")
    public Properties yamlProperties() throws IOException {
        YamlPropertiesFactoryBean bean = new YamlPropertiesFactoryBean();
        bean.setResources(new ClassPathResource("test.yml"));
        return bean.getObject();
    }

    @Bean
    public MessageSource messageSource() throws IOException {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setCommonMessages(yamlProperties());
        return messageSource;
    }
}
Oriflamme answered 25/7, 2017 at 16:55 Comment(0)
S
5

The best solution I managed to find was found before me by @vtosh: to use this library. The only problem (but still) is that it is not popular enough.

The other option could be to extend Java localization support manually extending the ResourceBundle.Control class (you can find an official example here). But I don't see much sense in it since the library @vtosh found uses this approach.

Why there is no a solution for Spring? Well, the answer you can find in this jira. It is still in Open state so I don't expect to be any solution from their side at least for now.

Sanctified answered 25/7, 2017 at 15:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.