我一直在努力用Maven生成一個可執行的jar文件。我包含一個單獨的sqljdbc.jar
文件並將它放在一個/lib
文件夾中,該項目無錯誤且可在Eclipse或IntelliJ中運行。Maven:生成的jar文件遇到classNotFound錯誤
但是使用Maven的時候,我產生了jar
文件有:
mvn clean package
,並用下面的代碼運行它:
java -jar target/etl-aggregation-0.0.1-SNAPSHOT.jar
,並得到了以下消息:
ClassNotFoundException e : java.lang.ClassNotFoundException:
com.microsoft.sqlserver.jdbc.SQLServerDriver null
我曾嘗試過幾種方法,如How can I create an executable JAR with dependencies using Maven?,但仍然不能解決問題。
這是我pom.xml
文件的生成部分:
<build>
<resources>
<resource>
<directory>${project.basedir}</directory>
<includes>
<include>lib/*.jar</include>
</includes>
</resource>
</resources>
<plugins>
<!-- download source code in Eclipse, best practice and i don't know its usage here..-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>false</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
</plugin>
<!-- Set a compiler level -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.etl_aggregation.app.App</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<!-- Maven Assembly Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4.1</version>
<configuration>
<!-- get all project dependencies -->
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<!-- MainClass in mainfest make a executable jar -->
<archive>
<manifest>
<mainClass>com.etl_aggregation.app.App</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<!-- bind to the packaging phase -->
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
問題解決
我手動添加-cp lib/sqljdbc4.jar
運行jar
和它的工作。
假設打包的jar文件不包含'com.microsoft.sqlserver.jdbc.SQLServerDriver'。您需要將'sqlserver.jdbc' jar文件放到'.m2'中,並重新打包jar文件,因爲maven首先從本地存儲庫獲取jar文件。 –
您也可以爲自己的問題創建一個答案並接受它。 –