java获取 自身jar包所在路径

public static String getCurrentFilePath() {
    ProtectionDomain protectionDomain = JarUtil.class.getProtectionDomain();
    CodeSource codeSource = protectionDomain.getCodeSource();
    URI location = null;
    try {
        location = (codeSource == null ? null : codeSource.getLocation().toURI());
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    String path = (location == null ? null : location.getSchemeSpecificPart());
    if (path == null) {
        throw new IllegalStateException("Unable to determine code source archive");
    }
    File root = new File(path);
    if (!root.exists()) {
        throw new IllegalStateException(
                "Unable to determine code source archive from " + root);
    }
    return root.getAbsolutePath();
}

方法体内部代码,为摘录springboot启动类代码中的获取自身jar包路径的部分。

下面介绍如何在springboot中查找这段代码

对springboot类型的项目打包后,会生成一个可执行的jar包

对这个jar包解压,解压后,会有以下三个目录

BOOT-INF

META-INF

org

可以先看看META-INF目录中的MANIFEST.MF文件,这个文件已经被springboot打包插件做了更改

Manifest-Version: 1.0
Implementation-Title: dynamicer
Implementation-Version: 0.0.1-SNAPSHOT
Start-Class: com.cm.dynamicer.DynamicerApplication
Spring-Boot-Classes: BOOT-INF/classes/
Spring-Boot-Lib: BOOT-INF/lib/
Build-Jdk-Spec: 1.8
Spring-Boot-Version: 2.1.5.RELEASE
Created-By: Maven Archiver 3.4.0
Main-Class: org.springframework.boot.loader.JarLauncher

其中 Start-Class是springboot中我们自己的启动类

而jar包的启动类已经变成了org.springframework.boot.loader.JarLauncher

而这个类所属的模块是spring-boot-loader

我们可以下载这一模块的源码,在maven配置中,设置同时下载源码选项,然后可以在maven本地仓库找到源码,例如:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-loader</artifactId>
    <scope>provided</scope>
</dependency>

在JarLauncher中可以看到它的父类是ExecutableArchiveLauncher,然后ExecutableArchiveLauncher的父类是Launcher

Launcher类中有个方法

protected final Archive createArchive() throws Exception {
		ProtectionDomain protectionDomain = getClass().getProtectionDomain();
		CodeSource codeSource = protectionDomain.getCodeSource();
		URI location = (codeSource != null) ? codeSource.getLocation().toURI() : null;
		String path = (location != null) ? location.getSchemeSpecificPart() : null;
		if (path == null) {
			throw new IllegalStateException("Unable to determine code source archive");
		}
		File root = new File(path);
		if (!root.exists()) {
			throw new IllegalStateException(
					"Unable to determine code source archive from " + root);
		}
		return (root.isDirectory() ? new ExplodedArchive(root)
				: new JarFileArchive(root));
	}

就是这段了

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值