Search code examples
mavenmaven-pluginmaven-lifecycle

How to automatically process multiple "goals"?


I use package to have Maven generate the target JAR-file, and the dependency:build-classpath to generate the cp.txt listing all of the dependency JARs, that I don't want bundled into the target JAR:

mvn package dependency:build-classpath

Is there a way to make the classpath building happen together with the packaging automatically -- without me explicitly requesting both on command-line?


Solution

  • The command below executes the build-classpath goal of the maven dependency plugin:

    mvn dependency:build-classpath
    

    But when with the command below you actually instruct maven to pass from all the phases, up to package phase, on the default lifecycle (to which package phase belongs). When maven passes from these phases it executes all the attached plugin goals:

    mvn package
    

    However, maven does not by default attach the dependency:build-classpath goal to any phase (though it does with some other goals depending on type of packaging). You need to explicitly do this, just by declaring the plugin goal to the pom.xml (also providing the corresponding configuration):

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>3.0.2</version>
        <executions>
            <execution>
                <goals>
                    <goal>build-classpath</goal>
                </goals>
                <configuration>
                    <outputFile>cp.txt</outputFile>
                </configuration>
            </execution>
        </executions>
    </plugin>
    
    

    Maven will then attach the above goal to the generate-sources phase (which is the goal's default phase) and when that phase comes, the dependency:build-classpath plugin goal will execute.

    Conclusion:

    Q: How to automatically process multiple "goals"?

    A: You declare these goals to pom.xml (and optionally override the default each goal attaches to, e.g. in case you want to change their order of execution) and when maven passes from that phase, as part of maven lifecycle, they will automatically execute.