今天用webmagic写了个爬虫,用的是Maven项目形式,最后想打包成一个可运行的Jar包放到服务器上运行,遇到了一些问题,在这里做一下总结。主要是对maven还不熟悉和对Idea的使用不够熟练造成的。
一开始是直接用了mvn package
命令直接打包项目,cd
进target
目录之后执行 java -jar xxx.jar
之后报了一个错误
No main manifest attribute
#或者
java.lang.NoClassDefFoundError
这个时候我意识到了jar包中缺少了一些类,用WINRAR
解压软件直接打开jar包,印证了我的猜测,我在pom.xml文件中的引入的依赖并没有打包进来。
于是在网上搜索如何将依赖打包进目标jar包的方法,大都用了
maven-assembly-plugin
这个打包插件,于是我就用这个插件来打包,配置好pom.xml文件,因为这个插件有几种默认实现好的打包方式,所以我就不自定义打包方式了,直接使用
jar-with-dependencies
这个方式就能满足我的需求。
以下是我完整的pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<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.godelgnis</groupId>
<artifactId>sage</artifactId>
<version>1.0-SNAPSHOT</version>
<name>sage</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- webmagic爬虫框架依赖 -->
<dependency>
<groupId>us.codecraft</groupId>
<artifactId>webmagic-core</artifactId>
<version>0.7.3</version>
</dependency>
<dependency>
<groupId>us.codecraft</groupId>
<artifactId>webmagic-extension</artifactId>
<version>0.7.3</version>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!--(start) for package jar with dependencies -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.1</version>
<configuration>
<archive>
<manifest>
<!-- 主类名 -->
<mainClass>com.godelgnis.SageProcessor</mainClass>
</manifest>
</archive>
<descriptorRefs>
<!-- 将依赖打包进jar包 -->
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id> <!-- this is used for inheritance merges -->
<phase>package</phase> <!-- bind to the packaging phase -->
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<!--(end) for package jar with dependencies -->
</plugins>
</pluginManagement>
</build>
</project>
根据其他教程,都是说配置好之后直接使用mvn package
即可打包出我们要的jar包。
但是我的情况是,执行这条命令跟配置之前没有区别。
可以看到依旧是用不了的,然后找到了这里 https://maven.apache.org/plugins/maven-assembly-plugin/
用插件翻译一下
好,终于找到了,怎么说也是官网,那我就再终端执行命令
mvn assembly:single
报了这个警告
[WARNING] Cannot include project artifact: com.godelgnis:sage:jar:1.0-SNAPSHOT; it doesn’t have an associated file or directory.
没关系,再stackoverflow上找到解决方法
https://stackoverflow.com/questions/43687006/cannot-include-project-artifact-com-test-mmm-jar1-0-it-doesnt-have-an-associ?rq=1
#解决方法
#Use mvn package first to build your module classes then assembly:single.
mvn package assembly:single
执行上面这条命令就解决了我的问题