maven 将代码打成可执行jar包

在Eclipse中编写代码,如果没有用到第三方jar可以直接export成jar包,但是如果用到第三方jar包,就需要手动将拷贝依赖的jar包,也可以编写ant脚本自动打包。更方便的是使用maven,现在maven管理项目很方便,如下面将自己编写的类打成可执行jar包,并自动拷贝依赖的jar包。

下面是pom.xml文件:

<project xmlns="http://maven.apache.org/POM/4.0.0"  
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0           
    http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.yeetrack</groupId>
    <artifactId>httpclient</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>httpclient</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.2.3</version>
            </dependency>
    </dependencies>

    <build>
        <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-jar-plugin</artifactId>
                    <configuration>
                        <archive>
                    <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                    <!--指明main方法所在的类-->
                            <mainClass>com.baidu.httpclient.SVNTest</mainClass>
                    </manifest>
                        </archive>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <executions>
                            <execution>
                        <id>copy</id>
                        <phase>package</phase>
                        <goals>
                         <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>
                            ./target/lib
                         </outputDirectory>
                         </configuration>
                            </execution>
                    </executions>
                </plugin>
        </plugins>
    </build>
</project>

执行maven install就会在项目target文件夹下生成jar包,和依赖的jar包(在lib文件夹中),直接运行java -jar myjar.jar即可。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

(Spamcheck Enabled)