java 如何从java代码获取Maven项目BaseDir()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7808664/
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
How to get Maven project BaseDir() from java Code
提问by Feras Odeh
How to get Maven project basedir() from my Java code?
如何从我的 Java 代码中获取 Maven 项目 basedir()?
采纳答案by ptomli
According to maven doc, there's a maven property ${project.basedir}
根据maven doc,有一个 maven 属性${project.basedir}
If you include a properties file in your resources, which has the ${project.basedir}
placeholder, and enable filtering for the resources plugin, you will find that there's a build time substitution of the basedir into the properties file. You can then load this using a Properties
instance in code.
如果您在资源中包含一个属性文件,其中包含${project.basedir}
占位符,并启用资源插件过滤,您会发现在构建时将 basedir 替换为属性文件。然后,您可以使用Properties
代码中的实例加载它。
in /src/main/resources, create a file called project.properties, containing
在 /src/main/resources 中,创建一个名为 project.properties 的文件,其中包含
my.basedir=${project.basedir}
Then, in the POM, enable filtering for /src/main/resources, as outlined in the maven resources filtering documentation linked above.
然后,在 POM 中,为 /src/main/resources 启用过滤,如上面链接的 maven 资源过滤文档中所述。
Then, in code, at runtime, load the properties file into a Properties
instance
然后,在代码中,在运行时,将属性文件加载到Properties
实例中
Properties props = new Properties();
props.load(this.getClass().getResourceAsStream("project.properties"));
String myBasedir = props.get("my.basedir");
An alternative would be to process some source files and do substitution in there by hooking into the process-sources
phase, but that's not likely to be easy to explain.
另一种方法是处理一些源文件并通过挂钩到process-sources
阶段在其中进行替换,但这不太容易解释。
回答by Brian M. Carr
I'm assuming that you want this when run from 'exec:exec' or 'test'. If that's the case, you can get it via
我假设您在从 'exec:exec' 或 'test' 运行时想要这个。如果是这种情况,您可以通过
System.getProperties().get("basedir")
回答by Bozho
You can't, because maven is used for building, and doesn't "exist" after the build.
你不能,因为 maven 用于构建,并且在构建后不“存在”。
If you need that during the build (for example via the exec plugin), then it is either accessible as a system propery or you can pass it as argument to the executed program.
如果您在构建期间需要它(例如通过 exec 插件),那么它可以作为系统属性访问,或者您可以将它作为参数传递给执行的程序。