3

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.

kamaci
  • 72,915
  • 69
  • 228
  • 366
  • I'm sorry but I didn't get your question. What kind of parameters do you need? – Andrew Logvinov Feb 07 '13 at 20:47
  • 2
    There's actually a [guide](http://maven.apache.org/guides/plugin/guide-java-plugin-development.html) for plugin development. Annotations let you get any property from your project in your plugin classes. – Andrew Logvinov Feb 07 '13 at 21:11
  • @AndrewLogvinov I want to retrieve as a generic way, I have edited my question. – kamaci Feb 07 '13 at 22:33

4 Answers4

3

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");
}
DeadPassive
  • 877
  • 3
  • 8
  • 22
  • 1
    maven-jar-plugin is using Implementation-Version instead of Implementation-Build. see http://maven.apache.org/shared/maven-archiver/index.html#manifest – bhdrk Nov 05 '14 at 13:40
2
@Component
MavenProject project;

...

    project.getVersion()

Assuming you are using the Java 5 annotations

Stephen Connolly
  • 13,872
  • 6
  • 41
  • 63
0

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.

WPrecht
  • 1,340
  • 1
  • 17
  • 29
0

I've created a properties file and indicated at my pom:

<build>
    <resources>
        <resource>
            <directory>src/main/resources/</directory>
            <filtering>true</filtering>
        </resource>
 ...
</build>
kamaci
  • 72,915
  • 69
  • 228
  • 366