引入冬季

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之中

Spring 配置元信息

Bean配置元信息:BeanDefinition
Bean属性元信息:PropertyValues
容器配置元信息
外部化配置元信息: PropertySource
Profile 元信息: @Profile

Spring Bean 配置元信息

GenericBeanDefinition
RootBeanDefinition
AnnotatedBeanDefinition

Spring Bean 属性元信息
PropertyValues
MutablePropertyValues
PropertyValue
Bean 属性上下文存储
AttributeAccessor
Bean 元信息元素
BeanMetadataElement

Spring 容器配置元信息

beans 元素

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8"?>
<!-- outter -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
profile="dev" default-lazy-init="default" default-merge="default" default-autowire="default"
default-autowire-candidates="" default-init-method="" default-destroy-method=""
>
<!-- inner -->
<import resource="applicationContext-lookup.xml"/>
<bean id="userRepository" class="com.github.springframework.repository.UserRepository" autowire="byType"></bean>
</beans>
Beans元素属性 默认值 使用场景
profile null(留空) SpringProfiles 配置值
default-lazy-init default 当outter Beans “default-lazy-init”属性存在时,继承该值,否则为false
default-merge default 当outter beans ‘default-merge’ 属性存在时,继承该值,否则为“false”
default-autowire default 当outter beans “default-autowire”存在时,继承该值,否则为no
default-autowire-candidates null 默认SpringBean名称的pattern
default-init-method null 默认springBeans 自定义初始化方法
default-destroy-method null 默认SpringBean自定义的销毁方法

Spring Xml 配置元信息

xml元素 使用场景
<context:annotation-config/> 激活Spring注解驱动
<context:component-scan/> Spring @Component 以及自定义注解扫描
<context:load-time-weaver /> 激活Spring LoadTimeWeaver
<context:mbean-export /> 暴露Springbeans 做为JMX beans
<context:mbean-server /> 将当前平台作为MBeanServer
<context:property-placeholder /> 加载外部化配置资源作为Spring属性配置
<context:property-override /> 利用外部化配置资源覆盖Spring属性值

底层实现 BeanDefinitionParserDelegate

基于XML文件装载

Spring Bean 配置元信息

xml元素 使用场景
<beans:beans /> 单XML资源下的多个SpringBean配置
<beans:bean /> 单个SpringBean定义Beandefinition 配置
<beans:alias /> 为SpringBean 定义(BeanDefinition)映射别名
<beans:import /> 加载外部SpringXML 配置资源

底层实现 XmlBeanDefinitionReader BeanDefinitionDocumentReader BeanDefinitionHolder

基于Properties文件装载

Spring Bean 配置元信息

Properties 属性名 使用场景
(class) Bean类全称限定名
(abstract) 是否为抽象的BeanDefinition
(parent) 指定 parent BeanDefinition
(lazy-init) 是否延迟初始化
(ref) 引用其他Bean的名称
(scope) 设置Bean的scope属性
${n} n标示第n个构造器参数
底层实现PropertiesBeanDefinitionReader

基于Java注解装载SpringBean的配置元信息

Spring注解 场景说明
@Repository 数据仓储模式
@Component 通用组建模式
@Service 服务模式
@Controller Web控制器模式
@Configuration 配置类模式
@Autowired Bean依赖注入,支持多种依赖查找方式
@Qualifier 细粒度的@Autowired 依赖查找
@Resource Java注解,类似于@Autowired
@Inject Java注解,类似于@Autowired
@Profile 配置话条件装配
@Conditional 编程条件装配
@PostConstructor 替换XML元素 <bean init-method=” /> 或者 initializingBean
@PreDestroy 替换XML元素 或者 DisposableBean

ClassPathScanningCandidateComponentProvider
AutowiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor

SpringBean配置元信息底层实现

  • Xml资源 BeanDefinition解析与注册

    • 核心API: XmlBeanDefinitionReader
      • 资源: Resource
      • 底层: BeanDefinitionDocumentReader
        • XML 解析: JavaDOM Level 3 API
        • BeanDefinition 解析 BeanDefinitionParserDelegate
        • BeanDefinition 注册 BeanDefinitionRegistry
          DefaultBeanDefinitionDocumentReader
  • Properties 资源 BeanDefinition 解析与注册

    • 核心API:PropertiesBeanDefinitionReader
      • 资源
        • 字节流:Resource
        • 字符流:EncodeResource
      • 底层:
        • 存储:java.util.Properties
        • BeanDefinition 解析: API内部实现
        • BeanDefinition 注册: BeanDefinitionRegistry
  • Annotation 解析与注册

    • 核心API:AnnotatedBeanDefinitionReader
      • 资源
        • 类对象: java.lang.Class
      • 底层
        • 条件评估: ConditionEvaluator
        • Bean范围解析: ScopeMetadataResolver
        • BeanDefinition解析:内部API实现
        • BeanDefinition处理:AnnotationConfigUtils.processCommonDefinitionAnnotations
        • BeanDefinition注册:BeanDefinitionRegistry

基于XML文件装载SpringIOC容器配置元信息

命名空间 所属模块 Schema资源URL
beans spring-beans https://www.springframework.org/schema/beans/spring-beans.xsd
context spring-context https://www.springframework.org/schema/context/spring-context.xsd
aop spring-aop https://www.springframework.org/schema/aop/spring-aop.xsd
tx spring-tx https://www.springframework.org/schema/tx/spring-tx.xsd
util spring-util https://www.springframework.org/schema/util/spring-util.xsd
tool spring-tool https://www.springframework.org/schema/tool/spring-tool.xsd

基于Java注解装载SpringIOC容器配置元信息

Spring注解 场景说明 Since
@ImportResource 替换XML元素 </import> 3.0
@Import 导入Configuration Class 3.0
@ComponentScan 扫描指定package下标注Spring模式注解的类 3.1
@PropertySource 配置属性抽象 3.1
@PropertySources @PropertySource集合注解 4.0

基于ExtensibleXML authoring扩展Spring XML元素

  • 编写 XML Schema 文件,定义XML结构
  • 自定义NameSpaceHandler, 实现命名空间绑定
  • 自定义BeanDefinitionParser, 实现XML元素与BeanDefinition解析
  • 注册XML扩展:命名空间与XML Schema 映射

Extensible XML authoring扩展原理

  • AbstractApplicationcontext.obtainFreshBeanFactory
    • AbstractRefreshableApplicationContext.refreshBeanFactory
      • AbstractXmlApplicationContext.loadBeanDefinitions
        • XmlBeanDefinitionReader.doLoadBeanDefinitions
          • BeanDefinitionParserDelegate.parseCustomElement

BewanDefinitionParserDelegate.parseCustomElement(Element, BeanDefinition);

  • 获取namespace
  • 通过namespace 解析NamespaceHandler
  • 构造ParserContext
  • 解析元素,获取BeanDefinition

基于Properties文件装载外部化配置
基于YAML文件装载外部化配置

  • org.springfrmework.beans.factory.config.YamlProcessor
    • org.springframework.beans.factory.config.YamlMapFactoryBean
    • org.springframework.beans.factory.config.YamlPropertiesFactoryBean