What is the Maven idiom for accessing configuration files?
For example suppose I'm using the standard project structure and have
src/main/config/config.xml
To access this I presume
new File("src/ma开发者_开发技巧in/config/config.xml");
would be incorrect
There is no "Maven Idiom" for accessing configuration files. Maven is a build platform, not an execution platform. So the conventions for accessing configuration files that apply are really just the conventions of the Java platform that you are using; e.g.
- the plain J2SE way of doing it, or
- the J2EE and/or webapp way of doing it, or
- the J2ME way of doing it, or
- ...
Maven only comes into the picture because you (presumably) have resource files in your project / version control that need to be included in the JAR or WAR or whatever artifacts that you are building. To get this to work in Maven, you simply need to understand how Maven copies non-Java files into the artifacts.
In the simple (JAR) case, the default behavior is to copy anything in
src/main/resources/
into the JAR, with the same relative name; e.g.src/main/resource/foo/bar.xml
becomes/foo/bar.xml
in the JAR file.For WAR files, the default is to copy anything
src/main/webapp
to into the WAR file. So if you wanted a file to be accessible in the webapp as a classpath resource with the name/foo/bar.xml
you would put it insrc/main/webapp/WEB-INF/classes/foo/bar.xml
. (I'm assuming that you know how webapp classpaths work ... or that this isn't your use-case.)
A config file is just a resource on your classpath like any other, so use:
URL resource = getClass().getResource("config.xml");
You'll need to do the usual Use as Source Folder
on your src/main/config
folder for this to work in Eclipse with m2e.
I think config files should be in src/main/resources by default.
精彩评论