1、创建项目
2、
3、
4、
5、
测试mysql连接数据源,勾选上面两个即可,然后next,完成就创建好了。
6、注意:
pom.xml文件内容
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.yww</groupId> <artifactId>springboot_jh</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot_jh</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.27</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
7、yml配置
代码:我修改了端口8088
server: port: 8088 spring: datasource: username: root password: 1234 url: jdbc:mysql://127.0.0.1:3306/db2019 driver-class-name: com.mysql.jdbc
8、test包下做测试
代码:
package com.yww.springboot_jh; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import javax.sql.DataSource; @SpringBootTest(properties = "workerClassName=A") class SpringbootJhApplicationTests { @Autowired DataSource dataSource; @Test void contextLoads() throws Exception { System.out.println("获取的数据库连接为:"+dataSource.getConnection()); } }
9、看到如下就是连接成功:
10:附上小姐姐测试时候遇到的错误以及解决办法:
java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
这个错误一般 1、好好检查yml配置,2、数据源配置时候连接的用户名密码不对