【问题标题】:Embed XML configuration directly in Spring application context在 Spring 应用程序上下文中直接嵌入 XML 配置
【发布时间】:2010-09-24 13:47:25
【问题描述】:

我有一个 Java 对象,它能够在给定 XML 配置描述的情况下进行自我配置(它也需要其他描述,但我目前对 XML 感兴趣)。我想知道是否可以将 XML 描述直接嵌入到 Spring 应用程序上下文描述中。我在想象这样的事情:

<bean id="myXMLConfiguredBean" class="com.example.Foo">
  <constructor-arg type="xml">
    <myconfig xmlns="http://example.com/foo/config">
      <bar>42</bar>
    </myconfig>
  </constructor-arg>
</bean>

但我不知道这 - 或类似的东西 - 是否可能。我意识到我可以将 myconfig 嵌入到 CDATA 部分中,但这似乎有点难看。

【问题讨论】:

    标签: java xml spring configuration


    【解决方案1】:

    如果你的 bean 有一个属性告诉它配置文件的位置,并且它从类路径(或文件系统上的绝对位置)加载配置,那不是更干净吗?这样一来,您的 Spring 配置看起来更清晰,并且更容易编辑 bean 的 XML 配置,因为它位于单独的文件中。

    也许您甚至可以使用 Spring Application Context 的资源特性来做到这一点。

    【讨论】:

      【解决方案2】:

      Spring 的 XSD 允许 &lt;constructor-arg&gt; 通过以下方式包含任何 XML:

      <xsd:element name="constructor-arg">
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element ref="description" minOccurs="0" />
              <xsd:choice minOccurs="0" maxOccurs="1">
                <xsd:element ref="bean" />
                <xsd:element ref="ref" />
                <xsd:element ref="idref" />
                <xsd:element ref="value" />
                <xsd:element ref="null" />
                <xsd:element ref="list" />
                <xsd:element ref="set" />
                <xsd:element ref="map" />
                <xsd:element ref="props" />
                <!-- Any XML -->
                <xsd:any namespace="##other" processContents="strict" />
              </xsd:choice>
            </xsd:sequence>
            ...
        </xsd:complexType>
      </xsd:element>
      

      processContents 属性可以具有three values 之一

      strict:必须有一个可用项目的顶级声明,或者该项目必须有一个xsi:type,并且该项目必须是“有效”(视情况而定)。

      所以,只要您的配置 XML 有一个架构,并且您正确导入它,这应该可以工作。

      然后,您需要使用 CustomEditorConfigurer 为您的 XML 注册一个 PropertyEditor

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多