SpringBoot整合第三方技術的詳細步驟
SpringBoot整合第三方技術
一、整合Junit
新建一個SpringBoot項目
使用@SpringBootTest標簽在test測試包內整合Junit
@SpringBootTest
class Springboot03JunitApplicationTests {
@Autowired
private BookService bookService;
@Test
void contextLoads() {
bookService.save();
}
}- 名稱:@SpringBootTest
- 類型:測試類注解
- 位置:測試類定義上方
- 作用:設置Junnit加載的SpringBoot啟動類
注意:整合的Junit測試類需要和Java包中的配置文件類放在同一目錄下,否則需要指定配置java文件的class
@SpringBootTest(classes = Springboot03JunitApplication.class)
class Springboot03JunitApplicationTests {
@Autowired
private BookService bookService;
@Test
void contextLoads() {
bookService.save();
}
}
二、整合Mybatis
創(chuàng)建新模塊的時候選擇需要的技術集

之后就可以看到mybatis相應的坐標已經導入完成
接著設置數據源
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456
定義數據層接口與映射配置
public interface UserDao {
@Select("select * from test.sys_role;")
public List<Role> getAll();
}
測試類中注入dao接口,測試功能
@SpringBootTest
class Springboot04MybatisApplicationTests {
@Autowired
private UserDao userDao;
@Test
void contextLoads() {
List<Role> roleList = userDao.getAll();
System.out.println(roleList);
}
}注意:
- 數據庫SQL映射需要添加@Mapper被容器識別到
- 數據庫連接相關信息轉換成配置
- SpringBoot版本低于2.4.3(不含),Mysql驅動版本大于8.0時,需要在url連接串中配置時區(qū),或在MySQL數據庫端配置時區(qū)解決此問題
jdbc:mysql://localhost:3306/test?serverTimezone=UTC
三、整合Mybatis-Plus
Mybatis-Plus與Mybati 區(qū)別
- 導入坐標不同
- 數據層實現簡化
注意:由于SpringBoot中未收錄MyBatis-Plus的坐標版本,需要指定對應的Version
SpringBoot沒有整合Mybatis-Plus,所以需要我們手動添加SpringBoot整合MyBatis-Plus的坐標,可以通過mvnrepository獲取
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>定義數據層接口與映射配置,繼承BaseMapper
@Mapper
public interface UserDao extends BaseMapper<Role> {
}在yml配置文件配置數據庫前綴

#設置mp相關配置
mybatis-plus:
global-config:
db-config:
table-prefix: sys_測試
@SpringBootTest
class Springboot05MybatisPlusApplicationTests {
@Autowired
private UserDao userDao;
@Test
void contextLoads() {
Role role = userDao.selectById(1);
System.out.println(role);
}
}四、整合Druid
同樣的,Druid也需要自己手工整合
Maven導入依賴
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> </dependency>
在yml配置文件指定數據源
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC username: root password: root type: com.alibaba.druid.pool.DruidDataSource
或者
spring: datasource: druid: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC username: root password: root
五、總結
整合第三方技術的步驟:
- 導入對應的starter
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
username: root
password: root
到此這篇關于SpringBoot整合第三方技術的文章就介紹到這了,更多相關SpringBoot整合第三方內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring動態(tài)配置計時器觸發(fā)時間的實例代碼
這篇文章主要介紹了Spring動態(tài)配置計時器觸發(fā)時間的實例代碼,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-06-06

