0

我有一个 Spring 项目,我想在其中获取在我的 Spring beans XML 文件中定义的特定 Spring bean。我的 Spring bean XML 文件位于/WEB-INF/spring/root-context.xml.

这是我在 Service 类中的代码:

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

这是我编译时遇到的错误:

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
4

1 回答 1

0

WEB-INF 可能不在您的类路径中。我建议将 xml 文件移动到类路径中(例如src/main/resources/spring/root-context.xml)。然后你可以通过以下方式访问它:ApplicationContext context = new ClassPathXmlApplicationContext("/spring/root-context.xml");如果你在 web 应用程序中,Spring Mvc 在WEB-INF/<the name of the dispatcher servlet>-servlet.xml

如果要从 WEB-INF 访问上下文,可以使用

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

更好的方法是使用WebApplicationContextUtils或实施ApplicationContextAware. 不确定您的用例是什么...

于 2014-06-15T14:45:13.077 回答