应用上下文类路径未找到。

5
由于某些原因(shiro过滤器),我将应用程序上下文文件保存在WEB-INF文件夹中。当我运行Tomcat时,一切正常,但是当我尝试从控制器中获取应用程序上下文时,使用以下代码:
context = new ClassPathXmlApplicationContext(fileContext);

我总是收到这个异常信息:
IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist

似乎在eclipse中,我无法将WEB-INF包含在类路径中。我查看了许多stackoverflow上的问题,但仍未找到解决方案。
如果我将applicationContext.xml文件移动到src/main/java文件夹下,我就能够获取上下文,但是,在web.xml文件中定义的shiro文件夹无法看到在applicationContext文件中定义的shiro bean(我已经进行了双重检查,bean已经正确工作)。如何告诉web.xml从src/main/java获取内容?或者,如何访问applicationContext.xml?

1
为什么你想要在控制器内部创建一个新的ApplicationContext?最好是自动装配现有的ApplicationContext。 - Sotirios Delimanolis
尝试使用@Autowired private static ApplicationContext context; 但它总是为空。 - Andrea Girardi
1
尝试这个:https://dev59.com/aG445IYBdhLWcg3wWI2L。另外,不要使它静态化。 - Sotirios Delimanolis
4个回答

2

WEB-INF不在你的CLASSPATH中,WEB-INF/classes在其中。那么为什么不将它放在源文件夹中并打包应用程序呢?


问题出现在过滤器定义的web.xml文件中。它在WEB-INF目录下寻找applicationContext。 - Andrea Girardi
好的,我将applicationContext.xml移动到WEB-INF/classes下,现在它可以正常工作了。但是我无法在我的applicationContext中包含任何文件。我绝对需要包含ehcache.xml,但是无法将其嵌入到applicationContext中。 - Andrea Girardi
这应该很简单。在应用程序上下文XML所在的位置添加ehcache XML。请参考以下示例:<property name="hibernateProperties"> <props> <prop key="net.sf.ehcache.configurationResourceName">./ehcache.xml</prop> <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</prop> </props> </property> - maggu

1
使用
context = new FileSystemXmlApplicationContext(fileContext);

替代

context = new ClassPathXmlApplicationContext(fileContext);

同样的问题,它开始从绝对URL(与Eclipse相同)读取,我无法访问项目文件夹。 - Andrea Girardi

1
不要在控制器中创建 ApplicationContext 的实例。Spring 的 DispatcherServlet 已经为您创建了一个。您只需要使用 @Autowired 访问应用程序上下文文件中的所有 bean 声明即可。

0
问题已经解决,将所有配置文件移动到WEB-INF/classes下,并添加前缀classpath:。
<import resource="classpath:spring-data.xml"/> 

感谢大家的帮助!我非常感激!

祝福,安德烈亚


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接