问题
I can get some variable's values from my pom file i.e.:
${project.version}
and I am developing a custom maven plugin and I can set it with expressions however I don't want it. How can I get it in a Java method as like my pom file?
PS: System.getProperty("project.version") doesn't work, I should find a generic solution because I will use it at other things too i.e. getting bamboo build number etc.
回答1:
I did this in my web project by using the maven-war-plugin to inject the version into the manifest, then getting it from there with some Java code. I see no reason why something similar can't be done with a non-web project.
E.g.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
version>2.4</version>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
Then in Java (excluding error handling):
public String getMavenVersion(ServletContext ctx) {
String appServerHome = ctx.getRealPath("/");
File manifestFile = new File(appServerHome, "META-INF/MANIFEST.MF");
Manifest mf = new Manifest();
mf.read(new FileInputStream(manifestFile));
Attributes atts = mf.getMainAttributes();
return atts.getValue("Implementation-Build");
}
回答2:
@Component
MavenProject project;
...
project.getVersion()
Assuming you are using the Java 5 annotations
回答3:
Are you asking if you can pass parameters in as a class or some other structure all at once?
If so, you can pass them in as a System Properties file using the -D arguement and use System.getProperties() to get them out on the other side. Google around, a lot of project support reading settings in like this, there's a lot of example code out there.
回答4:
I've created a properties file and indicated at my pom:
<build>
<resources>
<resource>
<directory>src/main/resources/</directory>
<filtering>true</filtering>
</resource>
...
</build>
来源:https://stackoverflow.com/questions/14760638/how-to-get-maven-project-version-from-java-method-as-like-at-pom