Spring资源管理
Spring资源管理
为什么 Spring 不使用 Java 标准资源管理?
Java 标准资源管理强大,然而扩展复杂,资源存储方式并不统一
Java 标准资源管理
Java 标准资源定位
。
Java URL 协议扩展
- 基于 java.net.URLStreamHandlerFactory/
- 基于 java.net.URLStreamHandler
基于 java.net.URLStreamHandlerFactory 扩展协议
URLStreamHandlerFactory用于创建URLStreamHandler流式处理器;
URLStreamHandler通过openConnection的传入URL,返回URLConnection
URLStreamHandlerFactory为静态的,所以URLStreamHandlerFactory有且仅有一个,默认为空,同时提供了set方法
• JDK 1.8 內建协议实现
实现类名必须为 “Handler”
Spring 资源接口
资源接口
內建实现
Spring Resource 接口扩展
可写资源接口
• org.springframework.core.io.WritableResource
• org.springframework.core.io.FileSystemResource
• org.springframework.core.io.FileUrlResource(@since 5.0.2)
• org.springframework.core.io.PathResource(@since 4.0 & @Deprecated)
编码资源接口
• org.springframework.core.io.support.EncodedResource
Spring 资源加载器
Resource 加载器
org.springframework.core.io.ResourceLoader
- org.springframework.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 通配路径资源扩展
实现 org.springframework.util.PathMatcher
重置 PathMatcher
- PathMatchingResourcePatternResolver#setPathMatcher
依赖注入 Spring Resource
基于 @Value 实现
如:
@Value(“classpath:/...”)
private Resource resource;
依赖注入 ResourceLoader
• 方法一:实现 ResourceLoaderAware 回调
• 方法二:@Autowired 注入 ResourceLoader
• 方法三:注入 ApplicationContext 作为 ResourceLoader
Spring 配置资源中有哪些常见类型?
- XML 资源
- Properties 资源
- YAML 资源
Java 标准资源管理扩展的步骤?
简易实现
• 实现 URLStreamHandler 并放置在 sun.net.www.protocol.${protocol}.Handler 包下
自定义实现
• 实现 URLStreamHandler
• 添加 -Djava.protocol.handler.pkgs 启动参数,指向 URLStreamHandler 实现类的包下
高级实现
• 实现 URLStreamHandlerFactory 并传递到 URL 之中