maks
maks

Reputation: 6006

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

Upvotes: 2

Views: 9490

Answers (3)

gkamal
gkamal

Reputation: 21000

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>

Upvotes: 1

Santosh
Santosh

Reputation: 17893

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>

Upvotes: 0

Aravind A
Aravind A

Reputation: 9697

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>

Upvotes: 0

Related Questions