简体   繁体   中英

Load xml file in spring

I want to load xml file into spring bean for further processing. I know that it is possible to load properties file simply defining a bean property in spring configuration file. Is it possible to do the same with xml file?

edit For example I want to have a bean:

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

and in my configuration file I want to set it like this:

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

and then I want to parse that xml using DOM

You can achieve it by changing the parameter type to a Resource - more details in documentation . You can get the file handle from the resource object

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

and in the configuration file you can set it like this. You can use classpath: if the file is part of a jar in your classpath. If it is outside you will need to use the file:

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

PropertyPlaceholderConfigurer already supports xml property files via the DefaultPropertiesPersister

The xml file format for the properties is as below.

   <?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>

you can use

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

Change your configuration file to following,

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM