java 在 Tomcat 中使用 commons-configuration XMLConfiguration 时“找不到配置源”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4520252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Cannot locate configuration source" when using commons-configuration XMLConfiguration with Tomcat
提问by Bruno Shine
I'm building two apps that uses commons-configuration XMLConfiguration. Since the apps are related, I've build another project, called commons, that has a custom configuration manager that initializes the XMLConfiguration like so:
我正在构建两个使用 commons-configuration XMLConfiguration 的应用程序。由于应用程序是相关的,我构建了另一个名为 commons 的项目,它有一个自定义配置管理器,可以像这样初始化 XMLConfiguration:
config = new XMLConfiguration("conf/config.xml");
What happens is that the "command-line" app works fine, loading the configuration file. But when I try to use my custom configuration manager on a webapp (using Tomcat) I get a
发生的情况是“命令行”应用程序工作正常,加载了配置文件。但是当我尝试在 web 应用程序(使用 Tomcat)上使用我的自定义配置管理器时,我得到一个
org.apache.commons.configuration.ConfigurationException: Cannot locate configuration source
org.apache.commons.configuration.ConfigurationException:找不到配置源
I've placed the conf directory on the WEB-INF folder, the root folder and the META-INF folder. I've also tried with "/conf/config.xml"
, "./conf/config.xml"
and "../conf/config.xml"
.
我已将 conf 目录放在 WEB-INF 文件夹、根文件夹和 META-INF 文件夹中。我也试过"/conf/config.xml"
,"./conf/config.xml"
和"../conf/config.xml"
。
The only time I got this to work - on the web app - was using an absolute path.
我唯一一次让它工作 - 在网络应用程序上 - 是使用绝对路径。
What am I missing?
我错过了什么?
Thanks, Bruno
谢谢,布鲁诺
采纳答案by Bozho
Use ServletContext.getResourceAsStream(..)
, and pass the stream. Or if the file is on the classpath, you can use getClass().getResourceAsStream(..)
使用ServletContext.getResourceAsStream(..)
, 并传递流。或者,如果文件在类路径上,您可以使用getClass().getResourceAsStream(..)
回答by MattM
Actually, org.apache.commons.configuration.XMLConfiguration
does not have a constructor which accepts an InputStream
, so getClass().getResourceAsStream()
will not work. There is an XMLConfiguration
constructor which takes a URL, however, so use getClass().getResource()
instead.
实际上,org.apache.commons.configuration.XMLConfiguration
没有接受 an 的构造函数InputStream
,因此getClass().getResourceAsStream()
不会起作用。XMLConfiguration
但是,有一个构造函数接受 URL,因此请getClass().getResource()
改用。