Search code examples
springspring-ioc

Can't get Spring bean


I have a Spring project in which I want to get a specific Spring bean defined in my Spring beans XML File. My Spring bean XML file is located at /WEB-INF/spring/root-context.xml.

Here is my code in the Service class:

ApplicationContext context = new ClassPathXmlApplicationContext("/WEB-INF/spring/root-context.xml");

Here is the error I get when I compile :

parsing XML document from class path resource [WEB-INF/spring/root-context.xml]; nested exception is java.io.FileNotFoundException: class path resource [WEB-INF/spring/root-context.xml] cannot be opened because it does not exist

Solution

  • Probably WEB-INF is not inside your classpath. I suggest to move the xml file in the classpath (for example src/main/resources/spring/root-context.xml). Then you can access it with: ApplicationContext context = new ClassPathXmlApplicationContext("/spring/root-context.xml"); If you're inside web application, Spring Mvc looks for th context in WEB-INF/<the name of the dispatcher servlet>-servlet.xml

    If you want to access the context from WEB-INF you can load it using

      GenericApplicationContext ctx = new GenericApplicationContext();
      XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
      xmlReader.loadBeanDefinitions(new FileSystemResource(path));
    

    A better way is using WebApplicationContextUtils or implement ApplicationContextAware. Not sure what your use case is...