springboot jdbcTemplate 配置
时间: 2024-05-12 19:14:56 浏览: 66
详解spring boot中使用JdbcTemplate
首先,需要在Spring Boot项目的pom.xml中添加JDBC和MySQL依赖:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
```
接着,在application.properties或application.yml中配置数据源:
application.properties:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
```
application.yml:
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: admin
driver-class-name: com.mysql.jdbc.Driver
```
最后,在需要使用JdbcTemplate的类中注入JdbcTemplate对象:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
//...
}
```
这样就完成了Spring Boot中JdbcTemplate的配置。
阅读全文