-->

Mvn compile before exec

2020-08-11 04:22发布

问题:

I am trying to set up my POM such that when I do mvn exec:exec or mvn exec:java it will first compile the source and iff successful, execute it.

I have the following and have tried moving the <execution> part about but can't get it to work:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
            <executions>
                <execution>
                    <phase>exec</phase>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
                <mainClass>my.main.class</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>

When I do either mvn exec:exec ... or mvn exec:java it doesn't first compile. I have tried putting the <execution> part in the exec plugin section but that didn't work either?

回答1:

It's an old topic, but someone else might be interested in an alternative solution for this.

It's not exactly what you were looking for, but you can compile and execute using a single command:

mvn compile exec:exec

This way Maven will always compile the project before executing it.



回答2:

You can bind the exec plugin to a phase following compile in build lifecycle (verify in the example below):

<profile>
    <id>proxy</id>
    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <executions>
                    <execution>
                        <phase>verify</phase>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                        <configuration>
                           <mainClass>my.main.class</mainClass>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</profile> 

and than run mvn verify.

I see the answer is very late and you may have found a solution. I'm just leaving as a reference for others who may need it.