How to get Maven project BaseDir() from java Code [closed]

北城以北 提交于 2019-12-03 02:42:06

According to Codehaus, there's a maven property ${basedir}

If you include a properties file in your resources, which has the ${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.

in /src/main/resources, create a file called project.properties, containing

project.basedir=${basedir}

Then, in the POM, enable filtering for /src/main/resources, as outlined in the maven resources filtering documentation linked above.

Then, in code, at runtime, load the properties file into a Properties instance

Properties props = new Properties();
props.load(this.getClass().getResourceAsStream("project.properties"));
String basedir = props.get("project.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.

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

System.getProperties().get("basedir")

You can't, because maven is used for building, and doesn't "exist" after the build.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!