maven 摘抄

源网址 http://javasight.net/2011/06/3-way-to-run-java-main-from-maven/




概览

Maven的exec插件允许你运行Java项目中的main方法,当然包括将项目依赖中的类路径自动包含。本文向你展示使用Maven exec插件来运行Java文件的3种方式,并提供示例。

1. 从命令行运行

因为你不是在Maven阶段中运行你的代码,首先你需要编译代码。记住exec:java不会自动编译你的代码,你需要首先编译它们。

mvn compile
一旦你的代码编译完毕,下面的代码将会运行你的类


不带参数

mvn exec:java -Dexec.mainClass="net.javasight.module.Main"
带有参数

mvn exec:java -Dexec.mainClass="net.javasight.module.Main" -Dexec.args="arg0 arg1 arg2"
带有类路径上的运行时依赖

mvn exec:java -Dexec.mainClass="net.javasight.module.Main" -Dexec.classpathScope=runtime
2. 在pom.xml的阶段中运行

你也可以在Maven阶段中运行你的主方法。例如,你可以在test阶段运行CodeGenerator.main()方法:


<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.1.1</version>
            <executions>
                <execution>
                    <phase>test</phase>
                    <goals>
                        <goal>java</goal>
                    </goals>
                    <configuration>
                        <mainClass>net.javasight.module.CodeGenerator</mainClass>
                        <arguments>
                            <argument>arg0</argument>
                            <argument>arg1</argument>
                        </arguments>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

要使用上述配置运行exec插件,简单的运行如下命令即可:

mvn test
3)在pom.xml的profile中运行

你可以在不同的profile中运行主方法。简单的包装上述的配置到profile标签中。

<profiles>
    <profile>
        <id>code-generator</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>exec-maven-plugin</artifactId>
                    <version>1.1.1</version>
                    <executions>
                        <execution>
                            <phase>test</phase>
                            <goals>
                                <goal>java</goal>
                            </goals>
                            <configuration>
                                <mainClass>net.javasight.module.CodeGenerator</mainClass>
                                <arguments>
                                    <argument>arg0</argument>
                                    <argument>arg1</argument>
                                </arguments>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

要调用上述的profile,运行如下命令

mvn test -Pcode-generator





加点自己的东西,
输入mvn test 会自动运行项目里的JUnit测试类。即使没有配置phase,也会运行JUnit测试。诸如 ***Test extends TestCase 的类,都会被自动测试。

猜你喜欢

转载自xkorey.iteye.com/blog/1539498