0

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
Veedrac
  • 58,273
  • 15
  • 112
  • 169

1 Answers1

0

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...

Evgeni Dimitrov
  • 21,976
  • 33
  • 120
  • 145
  • Yes I know, but what I want is that my XML file that is in web-inf can be accessed from both MVC layer and simple Service layers classes using ClassPathXmlApplicationContext . Is there a way to do this ? – Abdessamad BOUTGAYOUT Jun 15 '14 at 15:18