引入冬季
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内建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
- org.springframewor.core.io.DefaultResourceLoader
- org.springframework.core.io.ResourceLoader
Spring 通配路径资源加载器
- 通配路径ResourceLoader
- org.springframework.core.io.support.ResourcePatternResolver
- org.springframework.core.io.support.PathMatchingResourcePatternResolver
- org.springframework.core.io.support.ResourcePatternResolver
- 路径匹配起
- org.springframework.util.PathMatcher
- Ant模式匹配实现 - org.springframework.util.AntPathMatcher
- org.springframework.util.PathMatcher
Spring 通配路径资源扩展
依赖注入 Spring Resource
@Value(“classpath:/…”)
private Resource resource;
依赖注入 ResourceLoader
- 实现 ResourceLoaderAware 回调
- @Autowire 注入 ResourceLoader
- 注入ApplicationContext 作为 ResourceLoader
Java 标准资源管理扩展
- 实现URLStreamhandler, 并放置在 sun.net.www.protocal.${protocal}.Handler 下
1 | public class XURLConnection extends URLConnection{ |
1 | public class Handler extends URLStreamHandler{ |
1 | URL url = new URL("x:///META-INF/default.properties"); |
实现URLStreamHandler, 添加 -Djava.protocal.handler.pkgs 启动参数,指向URLStreamHandler 实现类的包
实现URLStreamHandlerFactory 并传递到URL之中