代码之家  ›  专栏  ›  技术社区  ›  Ian Dickinson

直接在Spring应用程序上下文中嵌入XML配置

  •  2
  • Ian Dickinson  · 技术社区  · 17 年前

    我有一个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区域,但这似乎有点难看。

    2 回复  |  直到 17 年前
        1
  •  2
  •   toolkit    17 年前

    春天的 XSD <constructor-arg> 要通过以下方式包含任何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

    严格:必须有可用项的顶级声明,或者该项必须具有 xsi:type ,并且该项目必须是有效的。

    因此,只要您的配置XML有一个模式,并且您正确地导入了它,这应该是可行的。

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

        2
  •  0
  •   Chochos    17 年前

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

    也许您甚至可以使用Spring应用程序上下文的资源特性来实现这一点。