Configure Maven to always clean when running package/install

Overview

When developing Java applications with Maven, you need to package and deploy them many times. Most commonly, every time there is a change in code, you will package and deploy the app to the development environment again.

The problem with this approach is for some reason, Maven doesn’t always recompile the code despite code changes. The best practice is to always run the clean goal before package/install goals.

However, I sometimes forget to do that and spent hours finding out why the changes don’t apply.

Let’s find out how you can configure Maven to run clean by default so the target folder always gets clean first before packaging/installing.

Add build configuration to always run clean before package

This is all you need to put into the pom.xml file

<build>
  <plugins>
    <!-- other plugins configuration -->
    
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-clean-plugin</artifactId>
      <executions>
        <execution>
          <id>always-run-clean</id>
          <phase>initialize</phase>
          <goals>
            <goal>clean</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

Now, if you run the package or install phase, the target folder will always get deleted first.

Default clean step run before package/install
Default clean step run before package/install

Leave a Comment