原文地址:http://www.cnphp6.com/archives/85639

Spring配置文件:

<context:property-placeholder location="classpath:/settings.properties" />
<context:property-placeholder location="classpath:/conf.properties"/>

settings.properties

redis.masterName=mymaster

conf.properties

home.abroad=1

测试类:

@Component
public class PropertyPlaceHolderTest {
    @Value("${redis.masterName}")
    String masterName;
    @Value("${home.abroad}")
    int homeAbroad;
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext-test.xml");
        PropertyPlaceHolderTest bean = ctx.getBean(PropertyPlaceHolderTest.class);
        System.out.println(ToStringBuilder.reflectionToString(bean));
    }
}

执行上述测试类 报错:

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'home.abroad' in string value [${home.abroad}]
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:173)
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:125)
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:151)
    at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:142)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:169)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:748)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:745)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:735)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
    ... 15 more

为什么只能解析出第一个property-placeholder配置中的key?第二个property-placeholder配置文件中的key是被忽略了吗?

但明明日志显示两个配置文件均被成功解析了啊。

INFO  org.springframework.context.support.PropertySourcesPlaceholderConfigurer  Loading properties file from class path resource [settings.properties]
INFO  org.springframework.context.support.PropertySourcesPlaceholderConfigurer  Loading properties file from class path resource [conf.properties]

那到底是什么原因呢?只有分析源代码了。发现一旦解析配置文件后会将其封装到一个PropertySourcesPropertyResolver对象中,如下所示:

//所属类:PropertySourcesPlaceholderConfigurer
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {        
    //......   
    this.processProperties(beanFactory, new PropertySourcesPropertyResolver(this.propertySources));
}

再创建一个StringValueResolver对象,实际使用上面的PropertySourcesPropertyResolver对象来解析占位符中的字符串。

//所属类:PropertySourcesPlaceholderConfigurer
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,
            final ConfigurablePropertyResolver propertyResolver) throws BeansException {
        //......
        StringValueResolver valueResolver = new StringValueResolver() {
            public String resolveStringValue(String strVal) {
                String resolved = ignoreUnresolvablePlaceholders ?
                        propertyResolver.resolvePlaceholders(strVal) :
                        propertyResolver.resolveRequiredPlaceholders(strVal);
                return (resolved.equals(nullValue) ? null : resolved);
            }
        };
        doProcessProperties(beanFactoryToProcess, valueResolver);
    }

最后将此StringValueResolver对象放入到一个List中,

//所属类:AbstractBeanFactory
public void addEmbeddedValueResolver(StringValueResolver valueResolver) {
        Assert.notNull(valueResolver, "StringValueResolver must not be null");
        this.embeddedValueResolvers.add(valueResolver);
    }

当自动注入@Value标注的字段时,

DEBUG org.springframework.beans.factory.annotation.InjectionMetadata  Processing injected method of bean 'propertyPlaceHolderTest': AutowiredFieldElement for int com.tcl.test.PropertyPlaceHolderTest.homeAbroad

需要解析@Value中的占位符中的内容了,涉及到源码是:

//所属类:AbstractBeanFactory
public String resolveEmbeddedValue(String value) {
        String result = value;
        for (StringValueResolver resolver : this.embeddedValueResolvers) {
            result = resolver.resolveStringValue(result);
        }
        return result;
    }

从之前描述可知this.embeddedValueResolvers中有两个valueResolver对象(分别对应两个context:property-placeholder元素),于是先取出第一个valueResolver(对应settings.properties)来解析${home.abroad},而它是配置在conf.poperties中的,肯定解析不到,于是就报错了,见源代码:

//所属的类与方法:PropertyPlaceholderHelper.parseStringValue
if (propVal != null) {
    //......
}
else if (this.ignoreUnresolvablePlaceholders) {
    // Proceed with unprocessed value.
    startIndex = buf.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());
}
else {
    throw new IllegalArgumentException("Could not resolve placeholder '" +
            placeholder + "'" + " in string value [" + strVal + "]");
}

但明明才遍历了List中第一个valueResolver对象呢,后面的那个可以成功解析啊。错误抛的也太急了点吧。

Spring肯定也考虑了这一点,从上面的源代码也可以看出,只要设置了ignoreUnresolvablePlaceholders为true的话,就不会走最后的else分支了。

修改Spring配置,显式指定第一个context:property-placeholder元素ignore-unresolvable属性为true,如下所示:

<context:property-placeholder location="classpath:/settings.properties" ignore-unresolvable="true"/>
<context:property-placeholder location="classpath:/conf.properties"/>

这时就不会报错了,${home.abroad}也能被成功解析了。见输出:

com.tcl.test.PropertyPlaceHolderTest@2f949a6b[masterName=mymaster,homeAbroad=1]

当然正常情况下没必要配置成两个或多个context:property-placeholder,完全可以用一个context:property-placeholder来指定多个配置文件,如下所示:

<context:property-placeholder location="classpath:/settings.properties,/conf.properties" />

SPRING多个占位符配置文件解析源码研究--转的更多相关文章

  1. spring源码分析之配置文件名占位符的解析(一)

    一.直接写个测试例子 package com.test; import org.junit.Test; import org.springframework.context.ApplicationCo ...

  2. Spring Cloud Finchley.SR1 版本的坑:placeholer占位符无法解析!

    接入nacos 之后,想把所有的配置丢上去. 启动程序是: @EnableDiscoveryClient @RestController @ComponentScan(basePackages = { ...

  3. Spring 利用PropertyPlaceholderConfigurer占位符

      Hey Girl   博客园    首页    博问    闪存    新随笔    订阅     管理 posts - 42,  comments - 3,  trackbacks - 0 Sp ...

  4. dubbo注册中心占位符无法解析问题

    dubbo注册中心占位符无法解析问题 1.背景 最近搞了2个老项目,想把他们融合到一起.这俩项目情况简介如下: 项目一:基于SpringMVC + dubbo,配置读取本地properties文件,少 ...

  5. Spring中AOP相关的API及源码解析

    Spring中AOP相关的API及源码解析 本系列文章: 读源码,我们可以从第一行读起 你知道Spring是怎么解析配置类的吗? 配置类为什么要添加@Configuration注解? 谈谈Spring ...

  6. dubbo注册中心占位符无法解析问题(二)

    dubbo注册中心占位符无法解析问题 前面分析了dubbo注册中心占位符无法解析的问题. 并给出了2种解决办法: 降低mybatis-spring的版本至2.0.1及以下 自定义MapperScann ...

  7. spring事务详解(三)源码详解

    系列目录 spring事务详解(一)初探事务 spring事务详解(二)简单样例 spring事务详解(三)源码详解 spring事务详解(四)测试验证 spring事务详解(五)总结提高 一.引子 ...

  8. Flink 源码解析 —— 源码编译运行

    更新一篇知识星球里面的源码分析文章,去年写的,周末自己录了个视频,大家看下效果好吗?如果好的话,后面补录发在知识星球里面的其他源码解析文章. 前言 之前自己本地 clone 了 Flink 的源码,编 ...

  9. Spring Boot核心技术之Rest映射以及源码的分析

    Spring Boot核心技术之Rest映射以及源码的分析 该博客主要是Rest映射以及源码的分析,主要是思路的学习.SpringBoot版本:2.4.9 环境的搭建 主要分两部分: Index.ht ...

随机推荐

  1. 可变字符串NSMutableString

    //可变字符串继承自字符串 //拼接 NSMutableString *string = [NSMutableString string]; [string appendString:@"今 ...

  2. const 使用一二

    Primer C++ 练习题4.20: int i = -1; const int ic = i; 对于这个,一开始认为,ic 作为const 类型变量,定义时应该给其赋常值,而此处给的是变量i,因此 ...

  3. Spotlight监控Oracle数据库的链接创建

    最近在做性能测试时,由于要挂载空间数据,开发人员直接将所有业务表都挂到了Oracle数据库中.最近做了几次测试发现响应时间和吞吐量都不是很理想,进行一番分析后怀疑可能在Oracle中出现问题,因此再网 ...

  4. 06.DOM操作应用高级

    获取表格tBodies.tHead.tFoot.rows获取行  cells获取td隔行变色 <!DOCTYPE HTML> <html> <head> <m ...

  5. 关于mySQL自连接的一些用法

    自连接是连接的一种用法,但并不是连接的一种类型,因为他的本质是把一张表当成两张表来使用. 举例说明: 这是一张职员信息表,如果我要查询这张表中的每个职员的上司,那么必须使用自连接来查询.所以为了能实现 ...

  6. iptables 思维导图 (zz)

  7. Android 6.0 使用HttpURLConnection 使用Get提交遇到405等问题。

    HttpURLConnection 在调用connection.setDoOutput(true)之后会自动把提交方式改为POST.然后调用方法的时候有可能会出现这种情况 在调用get的时候设置为co ...

  8. CYQ.Data V5 MDataTable 专属篇介绍

    前言 以前一两个月才出一篇,这三天有点变态地连续1天1篇(其实都是上周末两天写好的存货). 短期应该没有新的和此框架相关的文章要写了,这应该是最后一篇,大伙且看且珍惜. 前两篇讲数据库读写分离和分布式 ...

  9. .NET中使用APlayer组件自制播放器

    目录 说明 APlayer介绍 APlayer具备功能 APlayer使用 自制播放器Demo 未完成工作 源码下载 说明 由于需求原因,需要在项目中(桌面程序)集成一个在线播放视频的功能.大概要具备 ...

  10. Git 进阶指南

    转自: https://github.com/kaiye/kaiye.github.com/issues/7 在掌握了基础的 Git 使用 之后,可能会遇到一些问题.以下是猫哥筛选总结的部分常见问题, ...