【问题标题】:Load xml file in spring在spring中加载xml文件
【发布时间】:2011-12-22 18:06:40
【问题描述】:

我想将 xml 文件加载到 spring bean 中以进行进一步处理。我知道可以加载properties 文件,只需在spring 配置文件中定义一个bean 属性。是否可以对 xml 文件做同样的事情?

编辑 例如我想要一个豆子:

public class Bean {
   private File file
   public void setFile(File file) {
      this.file = file
   }
  //....
}

在我的配置文件中,我想这样设置:

<bean id="bean" class="blabla.Bean">
   <property name="file" value="smth here"/>
</bean>

然后我想使用 DOM 解析该 xml

【问题讨论】:

标签: java xml spring


【解决方案1】:

您可以通过将参数类型更改为 Resource 来实现 - 更多详细信息请参见 documentation。可以从资源对象中获取文件句柄

public class Bean {
   private File file
   public void setFile(Resource resource) {
      this.file = resource.getFile()
   }
  //....
}

在配置文件中你可以这样设置。您可以使用类路径:如果文件是类路径中 jar 的一部分。如果它在外面,您将需要使用该文件:

<bean id="bean" class="blabla.Bean">
   <property name="file" value="file:path to file"/>
</bean>

【讨论】:

    【解决方案2】:

    PropertyPlaceholderConfigurer 已经通过 DefaultPropertiesPersister 支持 xml 属性文件

    属性的xml文件格式如下。

       <?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
        <properties>
            <entry key="key1">Value 1</entry>
            <entry key="key2">Value 2</entry>
        </properties>
    

    你可以使用

      <context:property-placeholder 
      location="classpath:/com/myProject/spring_prop.xml" />
          <bean id="bean" class="org.MyBean">
             <property name="key1" value="${key1}" />
          </bean>
    

    【讨论】:

      【解决方案3】:

      将您的配置文件更改为以下,

      <bean id="bean" class="blabla.Bean">
         <property name="file" ref="file"/>
      </bean>
      
      <bean id="file" class="java.io.File">
         <constructor-arg type="string"><value>C:\myfile.xml</value></constructor-arg>
      </bean>
      

      【讨论】:

        猜你喜欢
        • 2015-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-19
        • 1970-01-01
        • 1970-01-01
        • 2017-06-04
        • 1970-01-01
        相关资源
        最近更新 更多