背景知识:Archive
Archive表示归档文件,通常为tar/zip等格式压缩包,Jar包为zip格式归档文件。SpringBoot抽象了Archive的概念,分为JarFileArchive(Jar包)和ExplodedArchive(文件目录)。
获取嵌套资源过程
- 获取当前Jar包代表的Archive;
- 根据过滤条件筛选出当前Jar包嵌套的资源;
获取当前Jar包代表的Archive
首先获取当前Jar包所在的路径,然后创建JarFileArchive,如下所示:
protected final Archive createArchive() throws Exception {
ProtectionDomain protectionDomain = getClass().getProtectionDomain();
CodeSource codeSource = protectionDomain.getCodeSource();
URI location = (codeSource == null ? null : codeSource.getLocation().toURI());
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.isDirectory() ? new ExplodedArchive(root)
: new JarFileArchive(root));
}
获取Jar包嵌套资源
将符合条件的嵌套Jar包过滤出来,如下所示:
protected Archive getNestedArchive(Entry entry) throws IOException {
JarEntry jarEntry = ((JarFileEntry) entry).getJarEntry();
if (jarEntry.getComment().startsWith(UNPACK_MARKER)) {
return getUnpackedNestedArchive(jarEntry);
}
try {
JarFile jarFile = this.jarFile.getNestedJarFile(jarEntry);
return new JarFileArchive(jarFile);
}
catch (Exception ex) {
throw new IllegalStateException(
"Failed to get nested archive for entry " + entry.getName(), ex);
}
}
参考: