In Maven, Why Run 'mvn clean'?

JavaMaven

Java Problem Overview


I am wondering what the major difference between running mvn compile and mvn clean compile are, in practicality.

I understand what the actual difference is, that mvn clean compile deletes all the generated files and starts again from scratch, but why would we want to do this? I can assume mvn compile will regenerate files if it's necessary, right?

One thing I noticed in my project was that if you had deleted a source file, without running clean, the compiled file remains, which usually wouldn't be a problem, but could be I suppose.

Java Solutions


Solution 1 - Java

For example: If you rename a class, the previous compiled version will remain in target/classes until you run clean. This maybe completely harmless, but it could cause issues if it is autodetected by classpath scanning and the like.

Solution 2 - Java

Certain plugins require a clean in order to work properly. For instance (at least in Maven 2), the maven-war-plugin explodes each dependent WAR into an existing directory tree. It requires a clean to get rid of files that have been removed from the dependent WARs.

Another problem is that when you rename a class, the old compiled version can hang around in the build tree, and will get included in JAR files, etcetera ... until you run mvn clean.

> I can assume "mvn compile" will regenerate files if it's necessary, right?

For mainstream plugins, that is a fair assumption. However, if you are using a plugin to generate source code components, I'd look carefully at the documentation, and at where you put the generated source code. For instance, there are a couple of unsupported plugins whose purpose is to drive the Eclipse EMF code generator.

Solution 3 - Java

If you don't do clean compile then it means you are still allowing to work with some obsolete classes. If your module suppose to migrate to new class then even you missed that, there won't be any compilation error due to old class exist in target/classes. This will remain unnoticed till same module is built at some other place/machine with clean compile goal.

Solution 4 - Java

On Maven, each time you want to compile, the best practice is to run mvn clean. It clears out the existing classes that you compiled from last compile. If you don't want to run 3 lines, just do "mvn test" after mvn clean. You don't have to always do mvn compile.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKevin DolanView Question on Stackoverflow
Solution 1 - JavaGareth DavisView Answer on Stackoverflow
Solution 2 - JavaStephen CView Answer on Stackoverflow
Solution 3 - JavaashahView Answer on Stackoverflow
Solution 4 - JavaFai HasanView Answer on Stackoverflow