简体   繁体   中英

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

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM