本文介绍了Spring Boot yml ResourceBundle文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring的MessageSource从类路径中的.properties文件加载错误消息.我的属性尊重某些模板",例如{Object}.{field}.{unrespectedConstraint}示例:

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

在进行重构的情况下(例如,更改类的名称),我必须在多个位置更改属性文件.

是否可以使用yaml文件(messages.yml)作为ResourceBundle获得类似以下内容:

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

我认为这足以满足您的要求,如果您需要在VM运行期间重新加载MessageSource,则可能需要做更多的挖掘工作.

>

@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;
    }
}

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.
解决方案

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;
    }
}

这篇关于Spring Boot yml ResourceBundle文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 19:03