目录
一、Springboot整合junit
只需要在测试类中添加注释@SpringBootTest
使用注释@Autowired自动装配
在service接口中添加注释@Service生成bean
如果测试类与Application类不在同一包下,则需要在测试类中
@SpringBootTest(classes = Application.class)
二、Springboot整合mybatis
我们使用springboot开发spring程序,所以不需要整合spring和springMVC
1.添加mybatis和mysql的起步依赖
2.编写Book表
package com.itheima.domain;
public class Book {
private Integer id;
private String name;
private String type;
private String description;
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", type='" + type + '\'' +
", description='" + description + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
3.编写数据层接口(使用mybatis注解开发
package com.itheima.dao;
import com.itheima.domain.Book;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface BookDao {
@Select("select * from tbl_book where id = #{id}")
public Book getById(Integer id);
}
4.编写配置文件(.yml),配置数据源
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
username: root
password: ia
5.编写测试类
package com.itheima;
import com.itheima.dao.BookDao;
import com.itheima.domain.Book;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Springboot08MybatisApplicationTests {
@Autowired
private BookDao bookDao;
@Test
void testGetById() {
Book book = bookDao.getById(1);
System.out.println(book);
}
}
三、使用druid数据源
导入坐标
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
在配置文件中配置,选择数据源为druid:
type: com.alibaba.druid.pool.DruidDataSource
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
username: root
password: ia
type: com.alibaba.druid.pool.DruidDataSource
运行: