如何将属性转换为JSON的Spring MVC方式?
问题描述:
我需要我的web服务来为我提供包含JSON格式本地化文本的messages.properties。我知道我可以编写我自己的解析器来做到这一点,但我应该在Spring框架中插入这个逻辑?或者是否有Spring基础架构功能已经可以做到这一点?如何将属性转换为JSON的Spring MVC方式?
答
您可以在您的课堂上使用@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。
Spring会将所有属性注入到消息属性中吗? – Xegara
是的,它会将所有属性注入到此属性实例中。一个注意事项:你需要用键'messages'启动所有的属性。它会 –
我试过了,但它没有注入任何消息属性。 – Xegara