2017-04-27 46 views
9

我使用Spring的MessageSource加載來自類路徑中的.properties文件的錯誤消息。我的屬性遵循一定的「模板」,如{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. 

在重構的情況下(改變例如對象的名稱),我不得不改變我的屬性在幾個地方文件。

有沒有辦法使用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。唯一的問題(但仍然)是它不夠普及。

另一個選項可能是擴展Java本地化支持手動擴展ResourceBundle.Control類(您可以找到官方示例here)。但是我發現它並沒有多少意義,因爲@vtosh的圖書館使用這種方法。

爲什麼沒有Spring的解決方案?那麼,你可以在this jira找到答案。它仍然處於開放狀態,所以我不期望至少在現在能夠從他們身邊獲得任何解決方案。

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