Spring加载多个配置文件的注意事项

在进行 Java Web 项目开发时,不可避免的会使用到数据库,这时就须要配置一系列的数据库链接参数。一般状况下,咱们会将数据库链接参数写入 .properties 的配置文件中,以减少这些参数和代码之间的耦合度,在程序运行时将其加载,读取其中的参数。
在 Spring 框架中,咱们能够经过多种方式将以下的配置文件导入到项目中。java

druid.driverClassName=com.mysql.jdbc.Driver
druid.url=jdbc:mysql://127.0.0.1:3306/test
druid.username=root
druid.password=1234

这里就针对最经常使用的方式进行介绍:使用 context:property-placeholder 标签实现配置文件加载。
这种经过在 Spring 的 applicationContext.xml 文件中添加标签的方式最为经常使用:mysql

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

这样 /src/main/resources/jdbc.properties 文件就会被 Spring 加载,而后经过以下方式配置链接池对象:web

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="${druid.driverClassName}"/>
    <property name="url" value="${druid.url}"/>
    <property name="username" value="${druid.username}"/>
    <property name="password" value="${druid.password}"/>
</bean>

其中,${} 中的内容和配置文件的键名保持一致,这样就能够将其中的数据读取到链接池对象中,从而建立链接池对象。spring

这里有一些额外的事项须要注意,Spring容器采用反射扫描的发现机制,在探测到 Spring 容器中有一个 PropertyPlaceholderConfigurer 的 Bean 就会中止对剩余PropertyPlaceholderConfigurer 的扫描。所以当你的项目中有两个配置文件须要加载,或者两个存在配置文件的独立模块合并时,其中一个配置文件就会没法加载,从而致使项目报错。sql

org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'dataSource' defined in class path resource [applicationContext.xml]: Could not resolve placeholder 'driverClassName' in value "${driverClassName}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'driverClassName' in value "${driverClassName}"
...
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'driverClassName' in value "${driverClassName}"
...

下面就列出几种经常使用的方式解决以上异常:数据库

  1. 使用通配符
<context:property-placeholder location="classpath*:*.properties"/>
  1. 在每一个标签内部增长 ignore-unresolvable=“true” 属性
<context:property-placeholder location="classpath:druid.properties" ignore-unresolvable="true"/>
<context:property-placeholder location="classpath:jedis.properties" ignore-unresolvable="true"/>
  1. 使用 , 将多个配置文件分隔开
<context:property-placeholder location="classpath:druid.properties,classpath:jedis.properties" />
  1. 若是使用注解方式导入多个配置文件,可按以下方式
@PropertySource({"classpath:druid.properties","classpath:jedis.properties"})