mysql驱动和druid连接池依赖配置:
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.21</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> </dependencies>
maven会自动导入对应的包:
xml配置Bean:
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource"> <property name="username" value="root"></property> <property name="password" value="123456"></property> <property name="url" value="jdbc:mysql://localhost:3306/db1"></property> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> </bean>
测试代码:
/** * 数据库连接池 */ @Test public void fun7(){ System.out.println("begin!"); DruidDataSource dataSource = ioc.getBean("dataSource", DruidDataSource.class); System.out.println(dataSource); }
运行结果:
begin! { CreateTime:"2022-05-28 19:57:28", ActiveCount:0, PoolingCount:0, CreateCount:0, DestroyCount:0, CloseCount:0, ConnectCount:0, Connections:[ ] } 进程已结束,退出代码为 0
创建资源文件:
内容:
mysql.username=root mysql.password=123456 mysql.url=jdbc:mysql://localhost:3306/db1 mysql.driverClassName=com.mysql.jdbc.Driver
xml配置:
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource"> <property name="username" value="${mysql.username}"></property> <property name="password" value="747699"></property> <property name="url" value="jdbc:mysql://localhost:3306/db1"></property> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> </bean> <context:property-placeholder location="db.properties"></context:property-placeholder>
再次运行:
begin! { CreateTime:"2022-05-28 20:09:48", ActiveCount:0, PoolingCount:0, CreateCount:0, DestroyCount:0, CloseCount:0, ConnectCount:0, Connections:[ ] } 进程已结束,退出代码为 0
没有问题!