Spring源码系列【3】启动细节解析占位符

本文深入探讨Spring启动时配置文件${}占位符的解析过程,从构造方法、setConfigLocations、getEnvironment()到占位符的具体解析细节。通过调试样例,展示了如何从系统属性和环境变量中获取属性值,以及如何递归解析嵌套的占位符,最终完成配置文件名的替换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上一篇Spring源码系列-2-整体debug,我们整体过了一遍Spring的启动过程,这篇我们来看一下Spring启动的部分细节

解析Spring配置文件${}占位符细节

调试样例

我们启动类中传递的配置文件名和上一篇样例不同,带了占位符的名称spring-${username}.xml,同时我们存在一个配置文件spring-dell.xml

// 启动类
public static void main(String[] args) {
   
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-${username}.xml");
    Student student = context.getBean(Student.class);
    System.out.println("姓名 " + student.getName());
}

// 配置文件为spring-dell.xml
<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean class="com.mashibing.Student" id="student">
        <property name="id" value="1"></property>
        <property name="name" value="zhangsan"></property>
    </bean>
</beans>

解析过程

ClassPathXmlApplicationContext构造方法细节
  1. 启动调试,调用ClassPathXmlApplicationContext构造方法

    image-20210527153949190

  2. 看一下super(parent)做了什么,super指的是AbstractApplicationContext

    public AbstractApplicationContext(@Nullable ApplicationContext parent) {
         
       this();
       setParent(parent);
    }
    

    简单看下有哪些属性,上一篇整体看refresh()函数的时候,基本都见过这些属性,所以了解下定义了哪些属性,后续看到就不要蒙了。

public abstract class AbstractApplicationContext extends DefaultResourceLoader
      implements ConfigurableApplicationContext {
   

   public static final String MESSAGE_SOURCE_BEAN_NAME = "messageSource";

   /**
    * 创建上下文的唯一标识
    *
    * Unique id for this context, if any. */
   private String id = ObjectUtils.identityToString(this);

   /** Environment used by this context. */
   @Nullable
   private ConfigurableEnvironment environment;

   /**
    * 用来存放beanFactory的后置处理器集合
    * BeanFactoryPostProcessors to apply on refresh. */
   private</
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值