Arjun Patel
Personal website and dumping ground for my technical notes.

Filtering resources in a Maven build

#maven

Prerequisites

To understand this note, these notes may help:

Suppose you have a file, src/main/filtered-resources/api.yml, and it looks like this:

openapi: 3.0.3
info:
  title: ${project.name} API
  description: ${project.description}
  version: ${project.version}
servers:
  - "http://localhost:8080"
paths:
  /home:
    get:
      summary: Get home page
      operationId: getHomePage
      responses:
        '200':
          description: Home page HTML
          content:
            text/html:
              schema:
                type: string

Notice the Maven variables in the info section. You probably want those to be interpolated, so that they end up containing the actual values for project name, description, and version. You tell Maven to do that by using a plugin definition like this:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-resources-plugin</artifactId>
  <executions>
    <execution>
      <id>render-api-spec-template</id>
      <goals>
        <goal>copy-resources</goal>
      </goals>
      <phase>generate-sources</phase>
      <configuration>
        <outputDirectory>${project.build.directory}/generated-sources</outputDirectory>
        <resources>
          <resource>
            <directory>src/main/filtered-resources</directory>
            <filtering>true</filtering>
            <includes>
              <include>api.yml</include>
            </includes>
          </resource>
        </resources>
        <delimiters>
          <!-- spring-boot-starter-parent changes the default, so explicitly specifying delimiter here -->
          <delimiter>${*}</delimiter>
        </delimiters>
        <useDefaultDelimiters>true</useDefaultDelimiters>
      </configuration>
    </execution>
  </executions>
</plugin>

This results in a filtered spec: target/generated-sources/api.yml:

openapi: 3.0.3
info:
  title: My Project API
  description: This is the description of my project
  version: 1.0.0-SNAPSHOT
servers:
  - "http://localhost:8080"
paths:
  /home:
    get:
      summary: Get home page
      operationId: getHomePage
      responses:
        '200':
          description: Home page HTML
          content:
            text/html:
              schema:
                type: string

And you might use this spec further down your Maven build, e.g. Generating Spring Boot web server from OpenAPI spec