【问题标题】:How to convert properties to JSON the Spring MVC way?如何以 Spring MVC 方式将属性转换为 JSON?
【发布时间】:2017-11-18 08:12:52
【问题描述】:

我需要我的 Web 服务来为我提供包含 JSON 格式的本地化文本的 messages.properties。我知道我可以编写自己的解析器来做到这一点,但是我应该在 Spring 框架的哪里插入这个逻辑?或者是否有 Spring 基础设施功能已经可以做到这一点?

【问题讨论】:

    标签: java json spring spring-mvc properties


    【解决方案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。

    【讨论】:

    • Spring会将所有属性注入到messages属性中吗?
    • 是的,它会将所有属性注入到这个 Property 实例中。请注意:您需要使用键 messages 启动所有属性。它会
    • 我试过了,但它没有向 messages 属性注入任何东西。
    • 你能尝试为这个属性创建一个getter吗?
    • 我什至添加了“messages.hello = World”,这是一个以“messages”键开头的键值对。它没有用。
    猜你喜欢
    • 2013-09-15
    • 2021-10-26
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    相关资源
    最近更新 更多