Getting FileNotFoundException in Spring

后端 未结 1 680
生来不讨喜
生来不讨喜 2021-01-24 02:26

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

Re         


        
1条回答
  •  清歌不尽
    2021-01-24 02:40

    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?

    0 讨论(0)
提交回复
热议问题