java - 将 XML 配置直接嵌入到 Spring 应用程序上下文中

标签 java xml spring configuration

我有一个 Java 对象,它能够在给定 XML 配置描述的情况下进行 self 配置(它也接受其他描述,但目前我对 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 部分,但这看起来有点难看。

最佳答案

Spring 的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 之一

strict: There must be a top-level declaration for the item available, or the item must have an xsi:type, and the item must be ·valid· as appropriate.

因此,只要您的配置 XML 具有架构,并且您正确导入它,就应该可以工作。

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

希望对你有帮助

关于java - 将 XML 配置直接嵌入到 Spring 应用程序上下文中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/327772/

相关文章:

java - Spring Jdbctemplate Rowmapper 没有设置对象中的所有值

java - Java中的 boolean 逻辑表达式

由编译器完成的 Java try-with-resource 实现

.Net 命名表(命名空间)问题

java - BeanIO 的 Xml 映射,列表未正确解释

java - 使用 querydsl 按 null 搜索

java - 根据Spring的bean定义bean

java - 捕获错误的异常

java - 如何中断当前正在运行的线程?

C# - 可移植类库 "XmlElement does not exist in the namespace System.XML"