简体   繁体   中英

Loading spring XML from location different from classpath

I am trying to read spring xml using ClassPathXmlApplicationContext class as below.

    ApplicationContext context = new ClassPathXmlApplicationContext("file:../WebContent/WEB-INF/dispatcher-servlet.xml");
    Service service = (Service ) context.getBean("service");

But I am getting FileNotFound exception. dispatcher-servlet.xml is located under WebContent/WEB-INF/dispatcher-servlet.xml. If I move the file to Src folder, it works fine.

I tried different ways like

    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:../WebContent/WEB-INF/dispatcher-servlet.xml");

 ApplicationContext context = new ClassPathXmlApplicationContext("/WEB-INF/dispatcher-servlet.xml");

But these don't work. Can someone provide some inputs.

Spring文档中

ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/appContext.xml");

Try this in your web.xml:

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

Or use ServletContextResource if you need to do this in code. See here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM