在 Java 类路径中包含 XML 配置的好习惯?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/872927/
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
Good practice to include XML config in Java classpath?
提问by Jon Skeet
My application is configured by some Spring XML configuration files.
我的应用程序是由一些 Spring XML 配置文件配置的。
Is it good practice in Java to include the XML files in the classpath, and reference them in my application using the classpath?
在 Java 中将 XML 文件包含在类路径中并使用类路径在我的应用程序中引用它们是一种很好的做法吗?
回答by Nathan Feger
I usually look in a system property first then the classpath. so:
我通常先查看系统属性,然后再查看类路径。所以:
java -DconfigFile=/filelocation/file.xml
can be read as:
可以读作:
String propfile = System.getProperty(configFile);
if (propfile != null) {
// read in file
new File(propfile);
...
} else {
// read in file from classpath
getClass.getResource("/configfile.xml")
}
回答by Jon Skeet
It's nice to be able to configure it both ways - either directly as a file, or via a resource on the classpath which may or may not be in a jar file. That gives you a lot of flexibility.
能够以两种方式配置它是很好的 - 直接作为文件,或通过类路径上的资源(可能在也可能不在 jar 文件中)。这为您提供了很大的灵活性。
回答by Dima
I agree with the previous poster (+1) - have an option in case some day you will need it. However, there is one catch. You could create yourself lots of headache if such powerful tooling will land in the wrong hands. There is no much difference between spring context files and java classes, it's a code. So, check out who are your users.. One over enthusiastic QA guru could make your life miserable if you're not prepared.
我同意之前的海报 (+1) - 有一个选项,以防有一天你会需要它。然而,有一个问题。如果这种强大的工具落入坏人之手,您可能会很头疼。spring上下文文件和java类没有太大区别,就是一段代码。所以,看看谁是你的用户。如果你没有准备好,一个过于热情的 QA 大师可能会让你的生活变得悲惨。
回答by Oliver Drotbohm
I tend to put XML config files into the classpath and expose configuration that is relevant to be adapted (e.g. for different environments) into external property files using a PropertyPlaceholderConfigureror the like (depends on actual requirements).
我倾向于将 XML 配置文件放入类路径中,并使用 aPropertyPlaceholderConfigurer等(取决于实际要求)将与适应(例如,针对不同环境)相关的配置公开到外部属性文件中。
A nice way to create profiles is to have properties files with a set of settings for each environment and let the administrator choose the one that is need by providing a system property whose value is then translated into a property file lookup. See API doc of PropertyPlaceholderConfigurerfor details.
创建配置文件的一个好方法是为每个环境设置一组设置的属性文件,并让管理员通过提供一个系统属性来选择需要的一个,然后将其值转换为属性文件查找。有关PropertyPlaceholderConfigurer详细信息,请参阅 API 文档。

