在spring的配置文件中,加載數據庫的properties文件,利用${username} 獲取數據庫用戶名時,會得到系統當前的用戶名;
這是因為 spring默認會優先加載系統環境變量,此時獲取到的username的值實際上指的是當前計算機的用戶名。而不是properties配置文件中指定的username的值。
解決方法:
1.修改配置文件中key的值,避免與系統當前用戶的username沖突;
2.采用本地配置覆蓋系統的配置
添加
local-override="true"
<context:property-placeholder local-override="true" ignore-unresolvable="true" location="classpath:dbconfig.properties"/>
xml寫法
添加
p:localOverride="true"
需要p標簽
xmlns:p="http://www.springframework.org/schema/p"
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:localOverride="true"> <property name="locations"> <list> <value>classpath:dbconfig.properties</value> </list> </property> </bean>
3. 采用 PropertiesFactoryBean 加載配置文件
<bean id="propertiesReader" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath:dbconfig.properties</value> </list> </property> </bean>
取值方式使用 #{ beanId['properties_key'] }
<property name="driverClass" value="#{propertiesReader['driver']}"/> <property name="jdbcUrl" value="#{propertiesReader['url']}"/> ......