具体文件格式
db.properties
#键=值
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql:// localhost:3306 / springdemo?rewriteBatchedStatements = true
jdbc.username = root
jdbc.password = 123456
jdbc.maxActive = 5
为什么在db.properties里加上JDBC,防止系统读取用户名的时候读取为系统的用户名,而不是读取数据库的用户名
解决办法:
第一种:context命名空间加上system-properties-mode =“从不”
< context :property-placeholder location =“classpath:db.properties” system-properties-mode =“NEVER” >
</ context :property-placeholder >
第二种:
加上JDBC。
application.xml中
<?xml version =“1.0” encoding =“UTF-8” ?>
< beans xmlns =“ http://www.springframework.org/schema/beans ”
xmlns:context =“ http://www.springframework.org/schema/context ”
xmlns:xsi =“ http://www.w3.org/2001/XMLSchema-instance ”
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 “ >
<! - 引入属性配置文件- >
< context :property-placeholder location =“classpath:db.properties” > </ context :property-placeholder >
<! - 配置连接池- >
< bean id =“datasource” class =“com.alibaba.druid.pool.DruidDataSource” init-method =“init” destroy-method =“close” >
< property name =“driverClassName” value =“$ {jdbc.driverClassName}” > </ property >
< property name =“url” value =“$ {jdbc.url}” > </ property >
< property name =“username” value =“$ {jdbc.username}” > </ property >
< property name =“password” value =“$ {jdbc.password}” > </ property >
< property name =“maxActive” value =“$ {jdbc.maxActive}” > </ property >
</ bean >
</ beans >
测试测试类
包装测试;
import com.alibaba.druid.pool.DruidDataSource;
import org.junit。测试 ;
import org.junit.runner。RunWith ;
import org.springframework.beans.factory.annotation。自动装配 ;
import org.springframework.test.context。ContextConfiguration ;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@RunWith(SpringJUnit4ClassRunner .class)
@ContextConfiguration(“classpath:applicationContext.xml”)
公共课考试{
@Autowired
private DataSource dataSource ;
@测试
public void test()抛出 Exception {
Connection conn = dataSource .getConnection();
系统。out .println(conn);
}
}
测试结果: