getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getSchemeSpecificPart()返回内容解析

当通过java -jar或者命令行mvn spring-boot:run的方式启动springboot项目时,会引导执行如下代码:

public static void main(String[] args) throws Exception {
	new JarLauncher().launch(args);
}

调用JarLauncher不带参数的构造方法创建JarLauncher对象,根据Java的继承特性会调用父类中的createArchive方法,官方代码实现如下:

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));
}

整个方法实现思路较为简单,即获取当前类所在的某个路径(后面讲解)下是否存在某个文件,然后根据是文件还是文件夹构建不同对象。那么这个路径是什么呢?于是把代码做了简单处理打印path,做了如下四个测试,得出以下现象:

  1. 把代码放置到测试类中执行时,输出:/D:/SoftDevelop/idea_workspace/first-app-by-gui/target/test-classes/
  2. 把代码放置到springboot启动类时,输出:/D:/SoftDevelop/idea_workspace/first-app-by-gui/target/classes/
  3. 打包成jar包,通过地址栏访问/sayPath时,输出:file:/C:/Users/Administrator/Desktop/first-app-by-gui-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/
  4. 打包成jar包,作为第三方依赖包时,输出:file:/C:/Users/Administrator/Desktop/first-app-by-gui-0.0.1-SNAPSHOT.jar!/BOOT-INF/lib/first-app-by-gui-0.0.2-SNAPSHOT.jar!/

综上所述,可以得出getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getSchemeSpecificPart()返回的内容为当前类所在的根路径,这里的根路径需要根据上述几种情况结合实际分析!

以上,完了!!

猜你喜欢

转载自blog.csdn.net/yu102655/article/details/112347600