spring源码解析(一)---占位符解析替换

本文详细介绍了Spring中占位符的解析过程,从PropertyResolver接口开始,阐述了ConfigurablePropertyResolver接口的角色,包括类型转换和占位符格式配置。接着,解释了AbstractPropertyResolver和PropertySourcesPropertyResolver的实现细节。通过一个demo示例和源码剖析,揭示了占位符解析的入口、替换逻辑,以及如何递归查找和解析占位符。
摘要由CSDN通过智能技术生成
 一、结构类图

 

①、PropertyResolver : Environment的顶层接口,主要提供属性检索和解析带占位符的文本。bean.xml配置中的所有占位符例如${}都由它解析

②、ConfigurablePropertyResolver : 该接口定义了如何对组件本身进行配置。如:刚刚提到获取value时可以指定任意类型,这依赖于ConversionService进行类型转换,当前接口就提供了对ConversionService的设置和获取。另外,可以配置属性占位符的格式,包括:占位符前缀(默认为"${")、占位符后缀(默认为"}")、占位符值分隔符(默认为":",用于分隔propertyName和defaultValue)。组件还可以设置哪些属性是必须存在的,还可以校验必须存在的属性是否真的存在(不存在的话会抛出异常)

③、AbstractPropertyResolver : 实现了ConfigurablePropertyResolver接口的所有方法

④、PropertySourcesPropertyResolver : 以PropertySources属性源集合(内部持有属性源列表List<PropertySource>)为属性值的来源,按序遍历每个PropertySource,获取到一个非null的属性值则返回

二、demo示例

public static void main(String[] args) {
        Properties properties = System.getProperties();
        
        properties.setProperty("prefixName", "read-code");
        
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:${prefixName}-spring.xml");
        
        ReadCodeService readCodeService = (ReadCodeService) ac.getBean("readCodeService");
        
        readCodeService.say();
    }
View Code

 

三、源码剖析

1、入口 : 

ClassPathXmlApplicationContext 构造函数setConfigLocations
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
            throws BeansException {

        super(parent);
        setConfigLocations(configLocations);
        if (refresh) {
            refresh();
        }
    }

2、AbstractRefreshableConfigApplicationContext

①、ClassPathXmlApplicationContext构造函数调用它的基类AbstractRefreshableConfigApplicationContext.setConfigLocations

 

    /**
     * Set the config locations for this application context.
     * <p>If not set, the implementation may use a default as appropriate.
     */
    public void setConfigLocations(String... locations) {
        if (locations != null) {
            Assert.noNullElements(locations, "Config locations must not be null");
            this.configLocations = new String[locations.length];
            for (int i = 0; i < locations.length; i++) {
                this.configLocations[i] = resolvePath(locations[i]).trim(); // 解析路劲
            }
        }
        else {
            
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值