2017-04-27 8 views
9

私はクラスパス内の.propertiesファイルからエラーメッセージを読み込むためにSpringのMessageSourceを使用しています。私の性質は、{Object}.{field}.{unrespectedConstraint}例として、特定の「テンプレート」を尊重:Springブートyml ResourceBundleファイル

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

は、リファクタリングの場合(例えば、オブジェクトの名前を変更する)、私は私の性質は、いくつかの場所でファイルを変更する必要があります。

のような何かを得るために、ResourceBundleのようYAMLファイル(messages.yml)を使用する方法はあります:

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

さて、免責事項:私自身はテストしていません。https://github.com/akihyro/yaml-resource-bundle – vtosh

答えて

1

私は見つけることができた最高のソリューションを@vtoshで私の前に発見された:使用にthis library。唯一の問題(それでもなお)は、それが十分に普及していないということです。

もう1つの選択肢は、手動でResourceBundle.Controlクラスを拡張してJavaローカリゼーションサポートを拡張することです(公式の例hereがあります)。見つかったライブラリ@vtoshがこのアプローチを使用しているので、私はそれにあまり意味がありません。

なぜSpring用のソリューションはありませんか?さて、答えはthis jiraです。それはまだOpen状態にあるので、少なくとも私は彼らの側からは何の解決策も期待していません。

1

これはあなたの必要条件を満たす必要があると思います。もし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; 
    } 
} 
関連する問題