Maven:保留编译期执行逻辑同时排除Java文件打包
Got it, let's break down how to handle this. Your UpdateFile class needs to run during the compile phase via the exec plugin, but you don't want it in the final Jar. The good news is this is straightforward—we just need to separate the compilation (which the exec plugin relies on) from the packaging step.
Core Idea
The exec-maven-plugin uses the compiled classes in target/classes to run your UpdateFile logic. We don't need to stop compiling this class; we just need to tell Maven's Jar plugin to exclude it when building the final artifact.
Step-by-Step Configuration
Keep your existing exec-maven-plugin setup, then add the maven-jar-plugin with an exclusion rule for your maintenance class:
<build> <!-- Retain your original exec plugin configuration --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.4.0</version> <executions> <execution> <id>build-dump</id> <phase>compile</phase> <goals> <goal>java</goal> </goals> </execution> </executions> <configuration> <mainClass>com.domain.internal.UpdateFile</mainClass> </configuration> </plugin> <!-- Add this jar plugin to exclude the maintenance class --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.3.0</version> <!-- Use the latest stable version here --> <configuration> <excludes> <!-- Match the compiled class path exactly --> <exclude>com/domain/internal/UpdateFile.class</exclude> </excludes> </configuration> </plugin> </build>
Why This Works
- Compilation: Maven's default compiler plugin will still compile
UpdateFilefromsrc/main/javaintotarget/classes, so the exec plugin can find and run it during thecompilephase without issues. - Packaging: The
maven-jar-pluginwill skip addingUpdateFile.classto the final Jar, even though the class exists intarget/classes.
If you're using other packaging plugins (like maven-war-plugin for web apps), you can add a similar <excludes> block to those plugins too, but the above setup covers standard Jar packaging.
内容的提问来源于stack exchange,提问作者Joe Almore

