2017-11-18 171 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

相关问题