简体   繁体   中英

Loading spring XML from location different from classpath to get a bean in Servlet

I have a Servlet class that is supposed to get data from service and write the data back to servlet response. The service class is already declared in spring xml ( dispatcher-servlet.xml ). So I want to get the service class bean from dispatcher-servlet.xml .

I tried below code

            ApplicationContext context = new FileSystemXmlApplicationContext("classpath:../WebContent/WEB-INF/dispatcher-servlet.xml");
        ServiceImpl serviceImpl = (ServiceImpl) context.getBean("service");

and below code

            ServletContextResource res = new ServletContextResource(getServletContext(),"/WEB-INF/dispatcher-servlet.xml");
        ApplicationContext context = new FileSystemXmlApplicationContext("file:"+res.getURL()+"dispatcher-servlet.xml");
        ServiceImpl serviceImpl = (ServiceImpl) context.getBean("service");

but those these are throwing FileNotFoundException

If I move the dispatcher-servlet.xml to src folder, it works fine. But I can't move it because the dispatcher-servlet.xml has been there in WEB-INF for long time many other classes are using it. dispatcher-servlet.xml is declared in Web.xml properly and it loads and works properly.

Only issue is I am unable to load it from the java code in servlet class.

The location of the dispatcher-xml is /WebContent/WEB-INF/dispatcher-servlet.xml

Any pointers or workarounds are highly appreciated. Thanks.

WEB-INF is added to classpath

You can try below code

ApplicationContext context = new FileSystemXmlApplicationContext
              ("classpath:/../dispatcher-servlet.xml");

Consider reading about what the classpath is and which parts of a web app are added to the classpath as advised by Sotirios Delimanolis

In your servlet code, have you tried:

ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext(),
"org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");

You'll need to ensure that your servlet is initialised after the dispatcher servlet in the web.xml (use the load-on-startup element).

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