tags:

views:

247

answers:

1

I want to create bean using BeanFactory, but I am getting an exeception: java.io.FileNotFoundException: \\WEB-INF\businesscaliber-servlet.xml.

Resource res = new FileSystemResource("//WEB-INF//businesscaliber-servlet.xml");
BeanFactory factory = new XmlBeanFactory(res);
if (factory != null && beanId != null) {
    obj = factory.getBean(beanId);
}

he its working using this

ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath*:/WEB-INF/businesscaliber-servlet.xml");

+1  A: 

I believe you need to specify an absolute path and not a Web application relative path to FileSystemResource.

Try using ServletContextResource instead.

Resource implementation for ServletContext resources, interpreting relative paths within the web application root directory.

The only issue is you need the ServletContext so:

ServletContext servletContext = ...
Resource res = new ServletContextResource(servletContext,
  "/WEB-INF/businesscaliber-servlet.xml");
BeanFactory factory = new XmlBeanFactory(res);
if (factory != null && beanId != null) {
    obj = factory.getBean(beanId);
}

It's worth noting that ideally you would retrieve this from an ApplicationContext. From 4.4 Resource Loader of the Spring Reference:

Resource template = ctx.getResource("some/resource/path/myTemplate.txt);

What would be returned would be a ClassPathResource; if the same method was executed against a FileSystemXmlApplicationContext instance, you'd get back a FileSystemResource. For a WebApplicationContext, you'd get back a ServletContextResource, and so on.

As such, you can load resources in a fashion appropriate to the particular application context.

So this is the preferred method of retrieving resources.

Alternatively since /WEB-INF/ is technically in the classpath you can use the classpath: prefix (as per your comment) or use ClassPathXmlApplicationContext (which will automatically return classpath resources).

Also theres no need to put double forward slashes in. Not sure why you're doing this. Perhaps a holdover from double backslashes, which are necessary?

cletus
is it correct syntax for new ServletContextResource() ?
Yashwant Chavan
I am able to find out the solution using this ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath*:/WEB-INF/businesscaliber-servlet.xml");
Yashwant Chavan