Spring properties 文件解析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/V_Junk/article/details/81609093

properties 文件解析

写在前面: 是因为 username 的问题,之前用的 liunx 系统然后换成 win 后,properties 文件中的 username 就解析成操作系统的用户名了。其实也简单,换一个 key 就好,只是我比较想知道是哪儿做的操作。

简单配置

  • properties 文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/x?useUnicode=true&characterEncoding=utf8&useSSL=true&allowMultiQueries=true
username=root
password=123456
  • xml 文件
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
    <bean/>

介于第一次写关于源码相关的博客,就多啰嗦一点儿。 点击标签 (context:property-placeholder),然后在对应的 jar 包的 META-INF/spring.handlers 文件中就可以找到有关标签的处理类,这里是 PropertySourcesPlaceholderConfigurer

结构图如下:
这里写图片描述

可以看出实现了 BeanFactoryPostProcessor 接口,所以这个类会在容器初始化的时候会被调用,此时就会把项目中定义的 properties 文件的属性 add 到 propertySources 中,通过打断点可以看出来此时 propertySources 已经在上面的步骤中添加了一个 key 为 environmentProperties值了,我们添加的为 key 为 localProperties。(这里这么说,其实太严谨,不过一打端点就能看明白了)。

然后,是关于 environmentProperties 的添加。这里是 org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions() 方法中第一行代内 new StandardEnvironment() 时,由 StandardEnvironment 的父类创建并保存在 AbstractBeanDefinitionReader.environment 属性中。
源码如下:
这里写图片描述

最后 : environmentProperties 中:通过 System.getProperties()System.getenv() 两个方法获取值。

猜你喜欢

转载自blog.csdn.net/V_Junk/article/details/81609093
今日推荐