项目场景:
提示:这里简述项目相关背景:
使用Spring框架对druid数据库连接池配置时,出现了配置文件读取错误的问题
问题描述
使用Spring框架对druid数据库连接池配置时,value=${username}获取到的值并非配置文件中的值,而是获取的windows系统用户的值,也就是我的名字。从而导致配置信息错误,无法连接数据库
<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 加载外部的properties文件 -->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!-- 配置druid连接池 -->
<bean id="dataSource_druid" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driver}"></property>
<property name="url" value="${url}"></property>
<property name="usernme" value="${username}"></property>
<property name="password" value="${password}"></property>
</bean>
<bean id="dataSource_c3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/db_web"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
配置文件中的信息
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/spring
username=root
password=root
打印的结果
原因分析:
username已经存在
username已经存在,context中应该就存在这一个username的值,虽然我们在配置文件中也有一个username的值
解决方案:
改名
将配置文件的username改名为user,将spring中的value配置信息改为value=${user}.避免重名即可。
打印结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/0d78bcb9880041cfbf1c09b3f79ddbd4.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5YW05aWL44Gu5aSn5YWs54y0,size_20,color_FFFFFF,t_70,g_se,x_16
总结
在以后使用username时一定要注意,具体为什么会出现这样的情况,可以查看源码弄清楚,当然,有的人不会有这样的情况。