3

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks!. In my servlet I have HttpServletRequest and HttpServletResponse, so I do "request.getRealPath()" instead of servletContext.getRealPath().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.