Spring 启动报错:Could not resolve placeholder jdbc.url 解决方案
问题描述
启动项目时遇到如下异常,堆栈信息显示 ContextLoaderListener 初始化失败,根源在于 Spring 无法解析 ${jdbc.url} 占位符:
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'dataSource' defined in file [...]: Could not resolve placeholder 'jdbc.url' in string value "${jdbc.url}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'jdbc.url' in string value "${jdbc.url}"
排查过程
遇到这类问题,常规思路通常是检查 .properties 文件是否存在,以及文件名是否与 applicationContext-dao.xml 中的引用一致。起初我也按这个方向排查了很久,确认配置文件内容如下:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.25.134:3306/SCTest?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
对比无误,且工程依赖中也包含了 JDBC 驱动包,但问题依旧。
解决方案
深入分析后发现,这是因为运行环境在加载 properties 文件时,如果找不到对应的配置项,就会直接抛出异常。要解决这个问题,可以根据 Spring 版本调整配置。
Spring 3 及以上版本
可以在 context:property-placeholder 标签中添加 ignore-unresolvable="true" 属性,这样即使部分占位符无法解析也不会中断启动。注意所有相关配置都需要加上该属性:
<context:property-placeholder location="classpath:db.properties" ignore-unresolvable="true" />
Spring 2.5 及更早版本
旧版本的 context:property-placeholder 不支持上述属性,此时需要改用 PropertyPlaceholderConfigurer。其配置逻辑与上面等价:

