如何在application.properties中表示Map-Spring Boot

时间:2019-06-17 15:41:28

标签: spring spring-boot javabeans application.properties

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

<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 question中的注释来替换此bean以使其与application.properties(配置)一起使用。可以使用普通对象,但是对我来说,很难在<map>

中显示此application.properties条目

1 个答案:

答案 0 :(得分:1)

以简单的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