解决nested exception is java.lang.IllegalArgumentException Could not resolve placeholder alipay.appId in string value $ {alipay.appId}

开发的时候出现了这种错误

nested exception is java .lang.IllegalArgumentException: Could not resolve placeholder ‘alipay.appId’ in string value
“${alipay.appId}”

大意是Spring不能处理第二个属性文件中的配置信息,因为Spring不允许定义多个PropertyPlaceholderConfigurer或context:property-placeholder。
Spring用反射扫描的发现机制,在探测到Spring容器中有一个org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的
Bean就会停止对剩余PropertyPlaceholderConfigurer的扫描(Spring 3.1已经使用PropertySourcesPlaceholderConfigurer替代 PropertyPlaceholderConfigurer了)。
换句话说,即Spring容器仅允许最多定义一个PropertyPlaceholderConfigurer(或context:property-placeholder),其余的会被Spring忽略掉(其实Spring如果提供一个警告就好了)。

问题的解决方案

  1. 通配符解决、逗号分隔

    • 使用通配符让spring一次性读取多个属性文件到一个 PropertyPlaceholderConfigurer bean中
      1
      2

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

    或者使用

    1
    <context:property-placeholder location="classpath:conf/db.properties,conf/alipay.properties"/>
  • 使用多个context:property-placeholder 分开定义,注意要加上 ignore-unresolvable 属性
    1
    2
    <context:property-placeholder location="classpath:conf/db.properties" ignore-unresolvable="true"/>
    <context:property-placeholder location="classpath:conf/alipay.properties" ignore-unresolvable="true"/>
    在每个PropertySourcesPlaceholderConfigurer配置中添加 或者在每个context:property-placeholder中都加上ignore-unresolvable=”true” 因为在你使用@Value(“${xx}”)
    或在xml中使用${xx}获取属性时,Spring会在第一个读取到的属性文件中去找,如果没有就直接抛出异常,而不会继续去第二个属性文件中找
  1. 一个PropertySourcesPlaceholderConfigurer中包含多个属性文件,和方案1原理相同
    1
    2
    3
    4
    5
    6
    7
    <bean id="propertyConfigurer" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="locations">
    <list>
    <value>classpath:db.properties</value>
    <value>classpath:alipay.properties</value>
    </list>
    </property>
  • 作者: Sam
  • 发布时间: 2019-09-18 23:52:05
  • 最后更新: 2019-12-09 23:03:26
  • 文章链接: https://ydstudios.gitee.io/post/cf36aee2.html
  • 版权声明: 本网所有文章除特别声明外, 禁止未经授权转载,违者依法追究相关法律责任!