在启动idea项目的时候报错
今天在整合spring和mybatis的时候出现这个问题:
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Access denied for user 'lew'@'localhost' (using password: YES)
### The error may exist in file [D:\IDE\work\mybatis\spring-study\spring-10-mybatis\target\classes\com\liang\mapper\UserMapper.xml]
### The error may involve com.liang.mapper.UserMapper.selectUser
### The error occurred while executing a query
### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Access denied for user 'lew'@'localhost' (using password: YES)
Process finished with exit code -1
在解决这个问题的时候自己也测试了很多遍,配置文件写的没问题,数据库的url也没有问题,经过多次测试发现:spring读取配置文件中的username的值是电脑中的名字
Access denied for user ‘lew’@‘localhost’ (using password: YES)
这里很明显获取的是我电脑的系统用户名'lew'@'localhost'
原因分析:
username已经存在
username已经存在,context中应该就存在这一个username的值,虽然我们在配置文件中也有一个username的值
所以在我的配置文件中的${username}获得的是系统用户名从而导致配置信息错误,无法连接数据库
<?xml version="1.0" encoding="UTF8"?>
<beans xmlns="http://www.springframework.org/schema/beans" default-autowire="byName"
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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
<!-- 加载外部的properties文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/liang/mapper/*.xml"/>
</bean>
<!--配置sqlSessionTemplate-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
解决方案一:
改名 把username 改成user
这里改了名字之后也要把相应的数据库配置文件里面
解决方案二:
在读取外部数据库配置文件的时候 local-override=“true” 把这个加上
<context:property-placeholder local-override=“true” location=“classpath:db.properties”/>
如下图
这个问题就这样解决了!