maven项目依赖本地jar包时编译生成可执行jar包方法

时间:2022-08-02 19:04:31

maven项目需要本地jar包时,在根目录新建lib目录,将jar包拷贝到lib目录并且添加到build path

此时直接打可执行jar包会出现编译报错、启动时缺少jar包等问题

解决方案:

    1.增加编译插件, 解决Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.5:compile (default-compile) on project test: Compilation failure: Compilation failure:   ***  程序包com.apache.XXX不存在  报错

<!-- 解决编译时缺少本地jar包报错 -->  
<plugin>  
    <groupId>org.apache.maven.plugins</groupId>  
    <artifactId>maven-compiler-plugin</artifactId>  
    <version>3.5</version>  
    <configuration>  
        <encoding>GBK</encoding>  
        <source>1.7</source>  
        <target>1.7</target>  
        <compilerArguments>  
            <extdirs>${basedir}/lib</extdirs>  
        </compilerArguments>  
    </configuration>  
</plugin>  

    2.指定主类, 将maven依赖包输出到指定目录,指定本地依赖包路径 (原理: maven-dependency-plugin 插件将maven依赖包复制到lib目录,maven-jar-plugin插件指定主类 并将所有依赖包写入到清单文件MANIFEST.MF 的 Class-Path中 )

<!-- maven依赖包外置 -->
<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-dependency-plugin</artifactId>
	<configuration>
		<outputDirectory>${project.build.directory}/lib</outputDirectory>
		<excludeTransitive>false</excludeTransitive>
		<stripVersion>false</stripVersion>
	</configuration>
	<executions>
		<execution>
			<id>copy-dependencies</id>
			<phase>prepare-package</phase>
			<goals>
				<goal>copy-dependencies</goal>
			</goals>
			<configuration>
				<outputDirectory>${project.build.directory}/lib</outputDirectory>
				<overWriteReleases>false</overWriteReleases>
				<overWriteSnapshots>false</overWriteSnapshots>
				<overWriteIfNewer>true</overWriteIfNewer>
			</configuration>
		</execution>
	</executions>
</plugin>
<!-- 指定主类,外置依赖包路径,指明依赖的本地包 -->
<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-jar-plugin</artifactId>
	<version>2.4</version>
	<configuration>
		<archive>
			<manifest>
				<addClasspath>true</addClasspath>
				<classpathPrefix>lib/</classpathPrefix>
				<mainClass>com.github.wolfclub.kafka.monitor.App</mainClass>
			</manifest>
			<manifestEntries>
				<Class-Path>lib/oneblog-commons.jar</Class-Path>
			</manifestEntries>
		</archive>
	</configuration>
</plugin>

    3.使用maven打包,复制target目录中生成的jar包和lib目录到 /path/to/project

    4.将本地依赖包复制到/path/to/project/lib (必须,maven-dependency-plugin插件不会将本地依赖包复制到对应目录)