引入冬季

Java标准资源管理

强大
|面向资源|文件系统、artifact(Jar、War、ear)、远程资源(HTTP/FTP)|
|API整合|java.lang.ClassLoader.getResource\ java.io.File / java.net.URL|
|资源定位|java.net.URL / java.net.URI|
|面向流存储|java.net.URLConnection|
|协议扩展|java.net.URLStreamHandler / java.net.URLStreamHandlerFactory|
扩展复杂

扩展协议

Spring资源接口

类型 接口
输入流 org.springframework.core.io.InputStreamSource
只读资源 org.springframework.core.io.Resource
可写资源 org.springframework.core.io.WritableResource
编码资源 org.springframework.core.io.EncodedResource
上下文资源 org.springframework.core.io.ContextResource

Spring InputStreamResource

Spring内建Resource实现

|Bean 定义|无|org.springframework.beans.factory.support.BeanDefinitionResource|
|字节码|无|org.springframework.core.io.ByteArrayResource|
|类路径|classpath:/|org.springframework.core.io.ClassPathResource|
|文件系统|file:/|org.springframework.core.io.FileSystemResource|
|URL|URL支持的协议|org.springframework.core.io.UrlResource|
|ServletContext|无|org.springframework.web.context.support.ServletContextResource|

Spring Resource 接口扩展
Spring 资源加载器

  • Resource 加载器
    • org.springframework.core.io.ResourceLoader
      • org.springframewor.core.io.DefaultResourceLoader
        • org.springframework.core.io.FileSystemResourceLoader
        • org.springframework.core.io.ClassRelativeResourceLoader
        • org.springframework.context.support.AbstractapplicationContext

Spring 通配路径资源加载器

  • 通配路径ResourceLoader
    • org.springframework.core.io.support.ResourcePatternResolver
      • org.springframework.core.io.support.PathMatchingResourcePatternResolver
  • 路径匹配起
    • org.springframework.util.PathMatcher
      • Ant模式匹配实现 - org.springframework.util.AntPathMatcher

Spring 通配路径资源扩展

依赖注入 Spring Resource

@Value(“classpath:/…”)
private Resource resource;

依赖注入 ResourceLoader

  • 实现 ResourceLoaderAware 回调
  • @Autowire 注入 ResourceLoader
  • 注入ApplicationContext 作为 ResourceLoader

Java 标准资源管理扩展

1
2
3
4
5
6
7
8
9
10
11
12
13
public class XURLConnection extends URLConnection{

private final UrlResource resource;

protected XURLConnection(URL url){
super(url);
this.resource = new ClassPathResource(url.getPath());
}

public InputStream getInputStream() throws IOException{
return resource.getInputStream();
}
}
1
2
3
4
5
public class Handler extends URLStreamHandler{
protected URLConnection openConnection(URL u) throws IOException{
return new XURLConnection(u);
}
}
1
2
3
URL url = new URL("x:///META-INF/default.properties");
InputStream is = url.openStream();
System.out.println(StreamUtils.copyString(is, Charset.forName("UTF-8")));
  • 实现URLStreamHandler, 添加 -Djava.protocal.handler.pkgs 启动参数,指向URLStreamHandler 实现类的包

  • 实现URLStreamHandlerFactory 并传递到URL之中