user2093082
user2093082

Reputation: 407

Getting property from pom.xml within java

I have a maven project, and in the pom.xml I set properties as such:

<project>
  <modelVersion>4.0.0</modelVersion>
  <artifactId>myArtifact</artifactId>
  <name>SomeProject</name>
  <packaging>jar</packaging>

  <properties>
    <some-system-property>1.9.9</some-system-property>
  </properties>
  <...>
</project>

I want to pull the some-system-property value from within the java code, similar to

String someSystemPropery = System.getProperty("some-system-property"); 

But, this always returns null. Looking over StackOverflow, most of the answers seem to revolve around enhanced maven plugins which modify the code - something that's a nonstarter in my environment.

Is there a way to just get a property value from a pom.xml within the codebase? Alternatively, can one get the version of a dependency as described in the pom.xml (the 1.9.9 value below):

<dependencies>
  <dependency>
     <groupId>org.codehaus.jackson</groupId>
     <artifactId>jackson-mapper-asl</artifactId>
     <version>1.9.9</version>
  </dependency>
</dependencies>

from code? Either one would solve my needs

Upvotes: 3

Views: 6319

Answers (3)

Aninda Bhattacharyya
Aninda Bhattacharyya

Reputation: 1251

Property values are accessible anywhere within a POM by using the notation ${X}, where X is the property, not outside. All properties accessible via java.lang.System.getProperties() are available as POM properties, such as ${java.home}, but not the other way around. So for your java code, it will need to scan the pom.xml as a xml parsing use case, but not sure why you want to do it.

Upvotes: 0

Those are Maven properties that apply during the build, not runtime system properties. One typical approach is to use Maven resource filtering to write the value into a properties file in the target directory.

Upvotes: 4

Crazyjavahacking
Crazyjavahacking

Reputation: 9697

Maven properties and not system properties.

Generally you should set the system property for a maven plugin that is triggering the execution:

  • surefire for unit tests,
  • exec for execution,
  • jetty or similar for starting a web container

There is also properties maven plugin than can set properties: http://mojo.codehaus.org/properties-maven-plugin/set-system-properties-mojo.html

Upvotes: 1

Related Questions