Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileSytemResources in Spring Framework

I am trying to retrieve xml file (containing bean definition) in my Spring MVC project. If I have the xml file under WEB-INF directory, then what path should I put into FileSystemResource in my servlet to retrieve the xml?

i.e. BeanFactory factory = new XmlBeanFactory(new FileSystemResource("xml"));

Thanks

like image 673
Lydon Ch Avatar asked Feb 21 '26 04:02

Lydon Ch


1 Answers

You shouldn't use FileSystemResource, you should use ServletContextResource:

new ServletContextResource(servletContext, "/myfile.xml");

Assuming, of course, that the servletContext is available to you.

If you really want to use FileSystemResource, then you need to ask the container where the directory is, and use that as a relative path, e.g.

String filePath = servletContext.getRealPath("/myfile.xml");
new FileSystemResource(filePath);

It it easier to let Spring do the work for you, though. Say you have a bean that needs this Resource. You can inject the resource path as a String, and let Spring convert it to the resource, e.g.

public class MyBean {

   private Resource myResource;

   public void setMyResource(Resource myResource) {
      this.myResource = myResource;
   }
}

and in your beans file:

<bean id="myBean" class="MyBean">
   <property name="myResource" value="/path/under/webapp/root/of/my/file.xml">
</bean>

Spring will convert the resource path into a ServletContextResource and pass that to your bean.

like image 82
skaffman Avatar answered Feb 25 '26 06:02

skaffman