[转]Spring中property-placeholder的使用与解析
我们在基于spring开发应用的时候,一般都会将数据库的配置放置在properties文件中.
代码分析的时候,涉及的知识点概要:
- NamespaceHandler 解析xml配置文件中的自定义命名空间
- ContextNamespaceHandler 上下文相关的解析器,这边定义了具体如何解析property-placeholder的解析器
- BeanDefinitionParser 解析bean definition的接口
- BeanFactoryPostProcessor 加载好bean definition后可以对其进行修改
- PropertySourcesPlaceholderConfigurer 处理bean definition 中的占位符
我们先来看看具体的使用吧
property的使用
在xml文件中配置properties文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <context:property-placeholder location="classpath:foo.properties" /> </beans>
这样/src/main/resources/foo.properties文件就会被spring加载
如果想使用多个配置文件,可以添加order字段来进行排序
使用PropertySource注解配置
Spring3.1添加了@PropertySource注解,方便添加property文件到环境.
@Configuration
@PropertySource("classpath:foo.properties")
public class PropertiesWithJavaConfig {@Beanpublic static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {return new PropertySourcesPlaceholderConfigurer();}
}
properties的注入与使用
java中使用@Value注解获取
@Value( "${jdbc.url}" ) private String jdbcUrl;
还可以添加一个默认值
@Value( "${jdbc.url:aDefaultUrl}" ) private String jdbcUrl;
在Spring的xml配置文件中获取
<bean id="dataSource"><property name="url" value="${jdbc.url}" /> </bean>
源码解析
properties配置信息的加载
Spring在启动时会通过AbstractApplicationContext#refresh启动容器初始化工作,期间会委托loadBeanDefinitions解析xml配置文件.
protected final void refreshBeanFactory() throws BeansException { if (hasBeanFactory()) { destroyBeans(); closeBeanFactory(); } try { DefaultListableBeanFactory beanFactory = createBeanFactory(); beanFactory.setSerializationId(getId()); customizeBeanFactory(beanFactory); loadBeanDefinitions(beanFactory); synchronized (this.beanFactoryMonitor) { this.beanFactory = beanFactory; } } catch (IOException ex) { throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); } }
loadBeanDefinitions通过层层委托,找到DefaultBeanDefinitionDocumentReader#parseBeanDefinition解析具体的bean
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) { if (delegate.isDefaultNamespace(root)) { NodeList nl = root.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element ele = (Element) node; if (delegate.isDefaultNamespace(ele)) { parseDefaultElement(ele, delegate); } else { delegate.parseCustomElement(ele); } } } } else { delegate.parseCustomElement(root); } }
这边由于不是标准类定义,所以委托BeanDefinitionParserDelegate解析
通过NamespaceHandler查找到对应的处理器是ContextNamespaceHandler,再通过id找到PropertyPlaceholderBeanDefinitionParser解析器解析
@Overridepublic void init() { // 这就是我们要找的解析器 registerBeanDefinitionParser("property-placeholder", new PropertyPlaceholderBeanDefinitionParser()); registerBeanDefinitionParser("property-override", new PropertyOverrideBeanDefinitionParser()); registerBeanDefinitionParser("annotation-config", new AnnotationConfigBeanDefinitionParser()); registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser()); registerBeanDefinitionParser("load-time-weaver", new LoadTimeWeaverBeanDefinitionParser()); registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser()); registerBeanDefinitionParser("mbean-export", new MBeanExportBeanDefinitionParser()); registerBeanDefinitionParser("mbean-server", new MBeanServerBeanDefinitionParser()); }
PropertyPlaceholderBeanDefinitionParser是这一轮代码分析的重点.
我们来看看它的父类吧.
BeanDefinitionParser
被DefaultBeanDefinitionDocumentReader用于解析个性化的标签
这边只定义了一个解析Element的parse apipublic interface BeanDefinitionParser { BeanDefinition parse(Element element, ParserContext parserContext); }
- AbstractBeanDefinitionParser
BeanDefinitionParser接口的默认抽象实现.spring的拿手好戏,这边提供了很多方便使用的api,并使用模板方法设计模式给子类提供自定义实现的钩子
我们来看看parse时具体的处理逻辑把:- 调用钩子parseInternal解析
- 生成bean id,使用BeanNameGenerator生成,或者直接读取id属性
- 处理name 与别名aliases
- 往容器中注册bean
- 进行事件触发
AbstractSingleBeanDefinitionParser
解析,定义单个BeanDefinition的抽象父类
在parseInternal中,解析出parentName,beanClass,source;并使用BeanDefinitionBuilder进行封装AbstractPropertyLoadingBeanDefinitionParser
解析property相关的属性,如location,properties-ref,file-encoding,order等PropertyPlaceholderBeanDefinitionParser
这边处理的事情不多,就是设置ingore-unresolvable和system-properties-mode
properties文件的加载,bean的实例化
接下来,我们再看看这个bean是在什么时候实例化的,一般类的实例化有2种,一种是单例系统启动就实例化;一种是非单例(或者单例懒加载)在getBean时实例化.
这边的触发却是通过BeanFcatoryPostProcessor.
BeanFactoryPostProcessor是在bean实例化前,修改bean definition的,比如bean definition中的占位符就是这边解决的,而我们现在使用的properties也是这边解决的.
这个是通过PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors实现的.
扫描容器中的BeanFactoryPostProcessor,找到了这边需要的PropertySourcesPlaceholderConfigurer,并通过容器的getBean实例化
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()); }
PropertySourcesPlaceholderConfigurer实例化完成后,就直接进行触发,并加载信息
OrderComparator.sort(priorityOrderedPostProcessors);invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
我们再来看看PropertySourcesPlaceholderConfigurer的继承体系把
BeanFactoryPostProcessor
定义一个用于修改容器中bean definition的属性的接口.其实现类在一般类使用前先实例化,并对其他类的属性进行修改.
这跟BeanPostProcessor有明显的区别,BeanPostProcessor是修改bean实例的.PropertiesLoaderSupport
加载properties文件的抽象类.
这边具体的加载逻辑是委托PropertiesLoaderUtils#fillProperties实现PropertyResourceConfigurer
bean definition中占位符的替换就是这个抽象类实现的.
实现BeanFactoryPostProcessor#postProcessBeanFactory,迭代容器的中的类定义,进行修改
具体如何修改就通过钩子processProperties交由子类实现PlaceholderConfigurerSupport
使用visitor设计模式,通过BeanDefinitionVisitor和StringValueResolver更新属性
StringValueResolver是一个转化String类型数据的接口,真正更新属性的api实现竟然是在PropertyPlaceholderHelper#parseStringValuePropertySourcesPlaceholderConfigurer
覆写postProcessorBeanFactory api定义解析流程
转载于:https://www.cnblogs.com/atai/p/9188831.html
[转]Spring中property-placeholder的使用与解析相关推荐
- 证明spring中property name=这个双引号的内容只与setter方法有关,与一个类定义的字段和getter方法无关...
证明如下: 思路定义两个实体类每个实体类的成员变量(字段)名和setter 和getter的名字都不一样: 原因是:bean的声明周期的原因:有一步是:注入属性. 其中一个类引用了另一个类. 被引用类 ...
- 剖析 SPI 在 Spring 中的应用
vivo 互联网服务器团队 - Ma Jian 一.概述 SPI(Service Provider Interface),是Java内置的一种服务提供发现机制,可以用来提高框架的扩展性,主要用于框架的 ...
- spring中context:property-placeholder标签详解
spring中context:property-placeholder标签的使用说明 1,有些参数在某些阶段中是常量. 在开发阶段我们连接数据库时的url,username,password等信息 分 ...
- Spring中PropertyPlaceholderConfigurer的使用
Spring中PropertyPlaceholderConfigurer的使用 在使用Spring配置获取properties文件时,在网上查到相关的资料,分享哈!! (1)获取一个配置文件 < ...
- Spring中配置DataSource数据源的几种选择
Spring中配置DataSource数据源的几种选择 在Spring框架中有如下3种获得DataSource对象的方法: 从JNDI获得DataSource. 从第三方的连接池获得DataSourc ...
- Spring中WebApplicationContext
ApplicationContext是Spring的核心,Context我们通常解释为上下文环境,我想用"容器"来表述它更容易理解一 些,ApplicationContext则是& ...
- Spring中使用Schedule调度
在spring中两种办法使用调度,以下使用是在spring4.0中. 一.基于application配置文件,配置入下: 1 <bean id="jobDetail" cla ...
- 惊呆了,Spring中竟然有12种定义bean的方法
前言 在庞大的 Java 技术体系中,Spring 有着举足轻重的地位,它给每位开发者带来了极大的便利和惊喜. 我们都知道 Spring 是创建和管理bean的工厂,它提供了多种方式定义 bean,能 ...
- Spring中的JDBC操作
一.Spring模板JdbcTemplate 为了使 JDBC 更加易于使用, Spring 在 JDBC API 上定义了一个抽象层, 以此建立一个 JDBC 存取框架JdbcTemplate. 作 ...
- spring整合mybatis(入门级简单教程1)--在spring中配置c3p0,并成功测试
引子:spring整合mybatis.因为,我们看完(我就是这样的)spring和mybatis之后,本想自己写一个小小的项目,以便加深理解,但是我发现在spring中整合mybatis并不是一件容易 ...
最新文章
- php jwt使用案例,PHP使用JWT创建Token的实例详解
- 100c之53:说谎族和诚实族
- C/S框架网介绍|.NET快速开发平台|Winform开发框架
- C语言在BST中找到最接近目标的值的算法(附完整源码)
- 思科设备路由器间IPsec ×××实现私网之间通信实战
- 好用的下拉第三方——nicespinner
- python3 循环输出当前时间。
- [总结] LCT学习笔记
- 三角函数与反三角函数图像
- Excel表格数据如何批量乘以一个数字
- 几年基础架构的经验之谈[42 things I learned from building a production database]
- gps面积测量仪手机版下载安装_gps面积测量仪手机版下载-GPS距离面积测量仪 安卓版v3.5.7-PC6安卓网...
- win10html网页运行空白,win10系统Ie浏览器无法打开HTML格式的网页文件的处理秒方...
- pytorch处理inf和nan数值
- l2范数求导_稀疏编码学习笔记(二)L2范数
- 数据库——JDBC基本连接步骤
- 为什么我发抖音没人点赞?抖音视频点赞数量怎样才能上涨?
- 医药、档案、全价值链知识管理等多款产品解决方案在鸿翼云生态大会上发布
- 《The Man Who Solved The Market》——量化大师西蒙斯新书总结
- 账套输出时文件服务器错误,你为什么会创建账套失败?
热门文章
- 强化学习《基于策略价值 - Asynchronous Adventage Actor-Critic》
- [机器学习-实践]支持向量机(SVM)从例子代码中学习
- [机器学习-坑] error: Microsoft Visual C++ 14.0 is required
- leetcode - 801. 使序列递增的最小交换次数
- 去哪儿-22-async-components
- Dirichlet Process and Stick-Breaking(DP的Stick-breaking 构造)
- SpringMVC 文件上传及下载
- ug中模型不见了怎么办_关于UG参数化建模的定义
- java程序样例_一个完整的java程序示例
- mysql update 多个字段_MySQL数据库基础