java URL协议扩展实现
JDK默认提供 HTTP 、 File 、 FTP 、Jar等协议的处理方法,SpringBoot 加载jar包内部jar也是通过扩展URL协议来实现的,具体可以org.springframework.boot.loader.jar.JarFile.registerUrlProtocolHandler方法。
扩展URL协议有两种实现
- 继承 java.net.URLStreamHandler
- 实现 java.net.URLStreamHandlerFactory 可以参考TomcatURLStreamHandlerFactory、SslStoreProviderUrlStreamHandlerFactory、DefaultFactory(jdk内置默认实现)
关键类
- URLStreamHandlerFactory 创建URLStreamHandler工厂
- URLStreamHandler 实现协议解析
- URL 管理各种协议解析实现
- URLConnection 负责加载url资源
- DefaultFactory 默认实现jar,file
继承URLStreamHandler
实现步骤
- 实现 URLConnection类,并实现connect、getInputStream方法(该步骤不是必须)
- 继承URLStreamHandler类,并实现openConnection方法
- 将URLStreamHandler实现类,添加到系统变量"java.protocol.handler.pkgs"中
demo 案例
代码如下:
- 继承URLStreamHandler,注意类名一定要为Handler,具体原因见(URL.getURLStreamHandler方法里面的lookupViaProperty方法)
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
public class Handler extends URLStreamHandler {
@Override
protected URLConnection openConnection(URL url) throws IOException {
return new PropertiesURLconnection(url);
}
}
- 自定义实现URLconnection
public class