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));
}
就是这段了