首页 > 解决方案 > 如何在 application.properties 中表示 Map - Spring Boot

问题描述

我在 xml 中定义了这个老式 bean:

<bean id="configReport" class="com.foo.config.ConfigReport">
    <property name="templates">
        <map>
            <entry key="1">
                <list>
                    <bean p:template="opt1" p:name="OPT1"
                        class="com.foo.config.ConfigReportTemplate" />
                </list>
            </entry>
            <entry key="-2">
                <list>
                    <bean p:template="opt-2" p:templateExtension="xlsx" p:name="OPT-2"
                        class="com.foo.config.ConfigReportTemplate" />
                </list>
            </entry>
        </map>
    </property>
    <property name="defaultTemplate">
        <bean p:template="empty" p:name="Empty"
            class="com.foo.config.ConfigReportTemplate" />
    </property>
</bean>

我想通过this questionapplication.properties中的注释替换这个bean来使用(config)。可以使用普通对象,但对我来说,很难在其中呈现这些条目<map>application.properties

标签: springspring-bootjavabeansapplication.properties

解决方案


Map以简单格式声明属性application.properties看起来很乱,我建议您考虑对这些属性使用 JSON 格式。它提供了一个更具可读性的视图,如下所示:

{
  "reportTemplates": {
    1: {
      "template": "com.foo.config.FirstTemplate",
      "name": "OPT1"
    },
    2: {
      "template": "com.foo.config.SecondTemplate",
      "name": "OPT2"
    },

    "KEY" : {
      "field":"value"
    },

    ...
  }
}

现在您可以在 java 配置中使用此配置文件来构建必要的模板。

您可以在此处阅读如何在 Spring 中使用 JSON 属性:https ://www.baeldung.com/spring-boot-json-properties


推荐阅读