1.整合JUnit
@SpringBootTest class Demo2ApplicationTests { @Autowired private BookDAO bookDAO; @Test void contextLoads() { bookDAO.save(); } }
创建的Springboot项目自动整合JUnit测试,在测试类中带有@SpringBootTest。
直接右键运行即可。
注意
但是当测试类和引导类不在同一个包下,就不能直接运行了,需要添加注解,否则就会找不到,找不到就需要直接告诉测试类引导类的class,如果没写的话测试类就会在当前包和父包中去找。
@SpringBootTest(classes = Demo2Application.class) class Demo2ApplicationTests { @Autowired private BookDAO bookDAO; @Test void contextLoads() { bookDAO.save(); } }
2.整合Mybatis
Step1:勾选相关技术,也就是导入MyBatis对应的starter
Step2:配置数据库信息
注意要加?serverTimezone=UTC,不然会报错,因为mysql8的驱动强制要求设置时区
Step3:创建实体类和DAO测试
public class User { private String userid; private String uname; private String upass; public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getUpass() { return upass; } public void setUpass(String upass) { this.upass = upass; } @Override public String toString() { return "User{" + "userid='" + userid + '\'' + ", uname='" + uname + '\'' + ", upass='" + upass + '\'' + '}'; } }
@Mapper public interface UserDAO { @Select("select * from users where userid = #{id}") public User getById(Integer id); }
@SpringBootTest class MybatisApplicationTests { @Autowired private UserDAO userDAO; @Test void contextLoads() { System.out.println(userDAO.getById(1)); } }
@Mapper注解是为了让容器识别
3.整合Mybatis-Plus
4.整合Druid
Step1:导入对应的依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> </dependency>
Step2:相关配置
第一种
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/spring?serverTimezone=UTC username: root password: niit type: com.alibaba.druid.pool.DruidDataSource
第二种:比较正规,看起来好看
spring: datasource: druid: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/spring?serverTimezone=UTC username: root password: niit
结论
通用的整合第三方技术的方式
- 首先导入具体的starter,通过初始化springboot项目时勾选具体的技术或者在pom文件中导入
- 在springboot配置文件中设置具体的配置