我使用的是使用ApplicationContext加载到我的Java应用程序中的XML配置文件。
XML配置文件通过使用PropertyPlaceholderConfigurer从多个属性文件中读取来解析其属性。
我想让每个属性文件都是可选的。我认为这是通过将ignoreUnresolsvablePlaceholders设置为true来完成的,但是当我运行应用程序时出现以下异常(db-default.properties存在但db.properties不存在):
Exception in thread "main" org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: class path resource [db.properties] cannot be opened because it does not exist
这就是我的XML配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="placeholder-configurer-1" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="1"/>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
<bean id="placeholder-configurer-2" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="2"/>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="location" value="classpath:/db-default.properties"/>
</bean>
<bean id="placeholder-configurer-3" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="3"/>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:/db.properties</value>
</list>
</property>
</bean>
<bean id="MyDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>
如何使db.properties成为可选属性文件?
答案 0 :(得分:18)
<property name="ignoreResourceNotFound" value="true"/>
答案 1 :(得分:5)
这也应该有效:
<context:property-placeholder ignore-resource-not-found="true" location="classpath:your.properties" ... />