文章目录
- 前言
- 一、准备
- 1. 引入库
- 2. 添加配置
- 2.1 jdbc.properties
- 2.2 spring-mvc.xml
- 二、测试
- 1.测试类
- 2.测试结果
- 总结
前言
【第5章】spring命名空间和数据源的引入
在spring章节已经简单的介绍了数据源的引入,两者差别不大。
一、准备
1. 引入库
<dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${spring.version}</version>
</dependency>
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.19</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.22</version>
</dependency>
2. 添加配置
2.1 jdbc.properties
jdbc_driverClassName=com.mysql.cj.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
jdbc_username=root
jdbc_password=123456a?
2.2 spring-mvc.xml
<!--引入外部文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="${jdbc_driverClassName}"/><property name="url" value="${jdbc_url}"/><property name="username" value="${jdbc_username}"/><property name="password" value="${jdbc_password}"/><property name="minIdle" value="3"/><property name="initialSize" value="5"/><property name="maxActive" value="20"/>
</bean>
二、测试
1.测试类
package org.example.springmvc.druid;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;/*** Create by zjg on 2024/5/6*/
@RestController
public class DruidController {@AutowiredDataSource dataSource;@RequestMapping("/druid")public String druid() throws SQLException {Connection connection = dataSource.getConnection();Statement statement = connection.createStatement();ResultSet resultSet = statement.executeQuery("select 1 from dual");String result = null;if(resultSet.next()){result=resultSet.getString(1);}statement.close();connection.close();return result;}
}
2.测试结果
1
总结
回到顶部