2017-11-18 96 views
2

我需要我的web服務來爲我提供包含JSON格式本地化文本的messages.properties。我知道我可以編寫我自己的解析器來做到這一點,但我應該在Spring框架中插入這個邏輯?或者是否有Spring基礎架構功能已經可以做到這一點?如何將屬性轉換爲JSON的Spring MVC方式?

回答

1

您可以在您的課堂上使用@PropertySource註釋將您的屬性文件加載到內存中。

@Configuration 
class MessagesConfiguration { 

    @Bean(name = "messageProperties") 
    public static PropertiesFactoryBean mapper() { 
     PropertiesFactoryBean bean = new PropertiesFactoryBean(); 
     bean.setLocation(new ClassPathResource("messages.properties")); 
     return bean; 
    } 

    @Resource(name="messageProperties") 
    private Properties messages = new Properties(); 

    public Properties getMessages() { 
     return messages; 
    } 

} 

Properties.class只是爲Map<String, String>的包裝,所以你可以把它轉換成JSON。

+0

Spring會將所有屬性注入到消息屬性中嗎? – Xegara

+0

是的,它會將所有屬性注入到此屬性實例中。一個注意事項:你需要用鍵'messages'啓動所有的屬性。它會 –

+0

我試過了,但它沒有注入任何消息屬性。 – Xegara

相關問題