变量命名冲突的解决思路(spring框架中使用${}动态引入用户名,想连接数据,结果访问被拒绝)

【在spring框架中使用${}动态引入用户名】访问被拒绝:Access denied for user 'Hua'@'localhost' (using password: YES)

image

image

java.lang.IllegalStateException: Failed to load ApplicationContext
	at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
	at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123)
	at ...
Caused by: java.sql.SQLException: Access denied for user 'Hua'@'localhost' (using password: YES)....

代码如下:

■ 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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        ">
        
     <!-- 从classpath的根路径 加载db.properties -->   
     <context:property-placeholder location="classpath:db.properties" system-properties-mode="NEVER"/>

	<!-- 配置数据库连接池 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
		<property name="driverClassName" value="${driverClassName}"/>
		<property name="url" value="${url}"/>
		<property name="username" value="${username}"/>
		<property name="password" value="${password}"/>
		<property name="initialSize" value="${initialSize}"/>
	</bean>
</beans>

■ 测试类:


@SpringJUnitConfig
public class App {

	@Autowired
	private DruidDataSource ds;
	

	@Test
	void test1() throws Exception {
//		ds = new DruidDataSource();
//		ds.setDriverClassName("com.mysql.jdbc.Driver");
//		ds.setUrl("jdbc:mysql://localhost:3306/springdemo?useSSL=false");
//		ds.setUsername("root");
//		ds.setPassword("admin");
		@Cleanup
		Connection connection = ds.getConnection();
		String sql = "select id, name, age from student";
		@Cleanup
		PreparedStatement ps = connection.prepareStatement(sql);
		@Cleanup
		ResultSet rs = ps.executeQuery();
		while(rs.next()) {
			System.out.print(rs.getLong("id") + ",");
			System.out.print(rs.getInt("age") + ",");
			System.out.println(rs.getString("name"));
		}

	}
}

● 分析思路:系统环境变量有个username,而数据库连接也有一个username,即出现同名了:

□ 解决同名思路1:通过设置属性,告诉配置不要引用系统环境变量的username,即system-properties-mode="NEVER"

image

✿ 那就不要出现同名的情况(从源头进行解决哈哈哈),连接数据库的变量名,命名为其他的

【一般情况,在sprig框架中,${username}动态引入的用户名默认是当前计算机系统的账户的用户名,不是数据库连接的用户名

posted @ 2022-02-26 13:26  一乐乐  阅读(55)  评论(0编辑  收藏  举报