1,在pom.xml文件中添加
<!-- 连接mysql 5.0没有cj 8.0有cj-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
2,在yml文件中编写连接数据库需要的属性
注意:先查看自己电脑上的Navicat版本
代码:
select version() from dual
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/world
driver-class-name: com.mysql.cj.jdbc.Driver
3,在控制器TestController中编写
package com.sm.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.sql.DataSource;
@RestController
@Slf4j
public class TestController {
@Resource
private DataSource dataSource;
@RequestMapping("/index")
public String index(){
log.info(dataSource.getClass().getName());
return "index方法返回:你好!";
}
}
4,然后运行引导类就行了