Access maven properties defined in the pom

Viewed 156760

How do I access maven properties defined in the pom in a normal maven project, and in a maven plugin project?

7 Answers

Update for Leif Gruenwoldt answer:

It's important to use

this.getClass().getClassLoader().getResourceAsStream("maven.properties");

instead of just

 this.getClass().getResourceAsStream("maven.properties");

Especially, if you write your maven.properties file right to project.build.outputDirectory:

<plugin>
   <groupId>org.codehaus.mojo</groupId>
   <artifactId>properties-maven-plugin</artifactId>
   <version>1.0.0</version>
   <executions>
      <execution>
         <phase>generate-resources</phase>
         <goals>
            <goal>write-project-properties</goal>
         </goals>
         <configuration>
            <outputFile>${project.build.outputDirectory}/maven.properties</outputFile>
         </configuration>
      </execution>
   </executions>
</plugin>

Explanation is right there.

I use the build-info goal in spring-boot-maven-plugin:

In my pom.xml:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <executions>
    ...
      <execution>
        <id>build-info</id>
        <goals>
          <goal>build-info</goal>
        </goals>
      </execution>
    </executions>
    <configuration>
    ...
    </configuration>
</plugin>

And in my code:

@Autowired
BuildProperties buildProperties;

...

@GetMapping
public Map<String, String> getVersion() {
    return Map.of(
            "build.name", buildProperties.getName(), 
            "build.version", buildProperties.getVersion(), 
            "build.date", buildProperties.getTime().toString());
}

More information about this plugin goal can be found here: https://docs.spring.io/spring-boot/docs/current/maven-plugin/reference/htmlsingle/#goals-build-info

Related