1、springboot簡(jiǎn)介
Spring Boot 可以輕松創(chuàng)建可以“直接運(yùn)行”的獨(dú)立的、生產(chǎn)級(jí)的基于 Spring 的應(yīng)用程序。
特征
創(chuàng)建獨(dú)立的 Spring 應(yīng)用程序
直接嵌入 Tomcat、Jetty 或 Undertow(無(wú)需部署 WAR 文件)
提供強(qiáng)壯的“入門(mén)”依賴項(xiàng)以簡(jiǎn)化您的構(gòu)建配置
盡可能自動(dòng)配置 Spring 和第三方中間件
提供生產(chǎn)就緒功能,例如指標(biāo)、健康檢查和外部化配置
完全無(wú)需代碼生成,無(wú)需 XML 配置
2、新建springboot web項(xiàng)目
按以下步驟依次操作
初始化項(xiàng)目完整的結(jié)構(gòu)
3、基本配置
3.1 引入相關(guān)依賴
mysql連接依賴
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
mybatis-plus
MyBatis-Plus (opens new window)(簡(jiǎn)稱(chēng) MP)是一個(gè) MyBatis (opens new window)的增強(qiáng)工具,在 MyBatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡(jiǎn)化開(kāi)發(fā)、提高效率而生。
特性
無(wú)侵入:只做增強(qiáng)不做改變,引入它不會(huì)對(duì)現(xiàn)有工程產(chǎn)生影響,如絲般順滑
損耗小:?jiǎn)?dòng)即會(huì)自動(dòng)注入基本 CURD,性能基本無(wú)損耗,直接面向?qū)ο蟛僮?br> 強(qiáng)大的 CRUD 操作:內(nèi)置通用 Mapper、通用 Service,僅僅通過(guò)少量配置即可實(shí)現(xiàn)單表大部分 CRUD 操作,更有強(qiáng)大的條件構(gòu)造器,滿足各類(lèi)使用需求
支持 Lambda 形式調(diào)用:通過(guò) Lambda 表達(dá)式,方便的編寫(xiě)各類(lèi)查詢條件,無(wú)需再擔(dān)心字段寫(xiě)錯(cuò)
支持主鍵自動(dòng)生成:支持多達(dá) 4 種主鍵策略(內(nèi)含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解決主鍵問(wèn)題
支持 ActiveRecord 模式:支持 ActiveRecord 形式調(diào)用,實(shí)體類(lèi)只需繼承 Model 類(lèi)即可進(jìn)行強(qiáng)大的 CRUD 操作
支持自定義全局通用操作:支持全局通用方法注入( Write once, use anywhere )
內(nèi)置代碼生成器:采用代碼或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 層代碼,支持模板引擎,更有超多自定義配置等您來(lái)使用
內(nèi)置分頁(yè)插件:基于 MyBatis 物理分頁(yè),開(kāi)發(fā)者無(wú)需關(guān)心具體操作,配置好插件之后,寫(xiě)分頁(yè)等同于普通 List 查詢
分頁(yè)插件支持多種數(shù)據(jù)庫(kù):支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多種數(shù)據(jù)庫(kù)
內(nèi)置性能分析插件:可輸出 SQL 語(yǔ)句以及其執(zhí)行時(shí)間,建議開(kāi)發(fā)測(cè)試時(shí)啟用該功能,能快速揪出慢查詢
內(nèi)置全局?jǐn)r截插件:提供全表 delete 、 update 操作智能分析阻斷,也可自定義攔截規(guī)則,預(yù)防誤操作
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
knife4j
Knife4j的前身是swagger-bootstrap-ui,前身swagger-bootstrap-ui是一個(gè)純swagger-ui的ui皮膚項(xiàng)目。
一開(kāi)始項(xiàng)目初衷是為了寫(xiě)一個(gè)增強(qiáng)版本的swagger的前端ui,但是隨著項(xiàng)目的發(fā)展,面對(duì)越來(lái)越多的個(gè)性化需求,不得不編寫(xiě)后端Java代碼以滿足新的需求,在swagger-bootstrap-ui的1.8.5~1.9.6版本之間,采用的是后端Java代碼和Ui都混合在一個(gè)Jar包里面的方式提供給開(kāi)發(fā)者使用.這種方式雖說(shuō)對(duì)于集成swagger來(lái)說(shuō)很方便,只需要引入jar包即可,但是在微服務(wù)架構(gòu)下顯得有些臃腫。
因此,項(xiàng)目正式更名為knife4j,取名knife4j是希望她能像一把匕首一樣小巧,輕量,并且功能強(qiáng)悍,更名也是希望把她做成一個(gè)為Swagger接口文檔服務(wù)的通用性解決方案,不僅僅只是專(zhuān)注于前端Ui前端.
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
完整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.6.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yinfeng</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>test</name>
<description>test</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>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.2 完成application.yml文件配置
server:
# 服務(wù)端口
port: 8888
spring:
application:
name: yinfeng-test
# 數(shù)據(jù)庫(kù)相關(guān)配置
datasource:
url: jdbc:mysql://127.0.0.1:3306/test?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: yinfeng
driver-class-name: com.mysql.cj.jdbc.Driver
3.3 配置knife4j
/**
* @author yinfeng
* @description knife4j配置
* @since 2022/3/12 21:49
*/
@Configuration
@EnableSwagger2
public class Knife4jConfig {
@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder().title("隱風(fēng) API文檔").version("1.0").build())
.select()
.apis(RequestHandlerSelectors
.basePackage("com.yinfeng.test.controller"))
.paths(PathSelectors.any())
.build();
}
}
/**
* @author yinfeng
* @description web配置
* @since 2022/3/12 21:57
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
3.4 配置mybatis plus插件
/**
* @author yinfeng
* @description Mybatis plus配置
* @since 2022/3/12 22:29
*/
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 加入分頁(yè)插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
}
4、創(chuàng)建測(cè)試表
4.1 連接數(shù)據(jù)庫(kù)
可以通過(guò)idea的數(shù)據(jù)庫(kù)工具直接連接數(shù)據(jù)庫(kù)
-
創(chuàng)建數(shù)據(jù)源
在這里插入圖片描述 -
配置連接信息
在這里插入圖片描述 執(zhí)行建表sql
CREATE TABLE `menus` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '菜單id',
`level` int(11) NOT NULL DEFAULT '1' COMMENT '菜單等級(jí)',
`name` varchar(11) NOT NULL DEFAULT '' COMMENT '菜單名',
`note` varchar(500) DEFAULT NULL COMMENT '備注',
`create_time` datetime NOT NULL COMMENT '創(chuàng)建時(shí)間',
`update_time` datetime NOT NULL COMMENT '更新時(shí)間',
`deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT '刪除標(biāo)志',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE KEY `menus_id_uindex` (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='菜單表';
- 創(chuàng)建測(cè)試數(shù)據(jù)
INSERT INTO `menus` (`id`, `level`, `name`, `update_time`, `note`, `create_time`, `deleted`) VALUES (1, 1, '首頁(yè)', '2021-08-22 13:44:51', '首頁(yè)', '2021-08-22 13:44:51', 0);
INSERT INTO `menus` (`id`, `level`, `name`, `update_time`, `note`, `create_time`, `deleted`) VALUES (1444693273867198466, 1, '科室管理', '2021-10-03 15:58:38', '科室管理科室管理', '2021-10-03 15:58:16', 0);
5、接口開(kāi)發(fā)
5.1 創(chuàng)建菜單表對(duì)應(yīng)的實(shí)體類(lèi)
/**
* @author yinfeng
* @description 菜單表
* @TableName menus
* @since 2022年3月12日 下午9:40:48
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ApiModel("菜單表")
@TableName("menus")
public class Menus {
/**
* 菜單id
*/
@TableId(type = IdType.ASSIGN_ID)
@JsonSerialize(using = ToStringSerializer.class)
@ApiModelProperty(value = "菜單id", example = "")
private Long id;
/**
* 菜單等級(jí)
*/
@TableField("level")
@ApiModelProperty(value = "菜單等級(jí)", example = "")
private Integer level;
/**
* 菜單名
*/
@TableField("name")
@ApiModelProperty(value = "菜單名", example = "")
private String name;
/**
* 備注
*/
@TableField("note")
@ApiModelProperty(value = "備注", example = "")
private String note;
/**
* 創(chuàng)建時(shí)間
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@ApiModelProperty(value = "創(chuàng)建時(shí)間", example = "")
private Date createTime;
/**
* 更新時(shí)間
*/
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@ApiModelProperty(value = "更新時(shí)間", example = "")
private Date updateTime;
/**
* 刪除標(biāo)志
*/
@TableField("deleted")
@TableLogic
@JsonIgnore
@ApiModelProperty(value = "刪除標(biāo)志", example = "")
private Integer deleted;
/**
* 當(dāng)前頁(yè)
*/
@ApiModelProperty(value = "當(dāng)前頁(yè)", example = "1")
@TableField(exist = false)
private Integer currentPage;
/**
* 分頁(yè)頁(yè)數(shù)
*/
@ApiModelProperty(value = "分頁(yè)頁(yè)數(shù)", example = "20")
@TableField(exist = false)
private Integer pageSize;
}
5.2 創(chuàng)建菜單表對(duì)應(yīng)的controller
包含基本的增刪改查接口
/**
* @author yinfeng
* @since 2022年3月12日 下午9:40:48
* @description 菜單表
*/
@Api(tags = "菜單表")
@RestController
@RequestMapping("/menus")
public class MenusController{
@Resource
private MenusService menusService;
@PostMapping("/list")
@ApiOperation(value = "列表", notes = "菜單表")
public IPage<Menus> list(@RequestBody Menus menus) {
return menusService.list(menus);
}
@PostMapping("/getOne")
@ApiOperation(value = "單個(gè)查詢", notes = "菜單表")
public Menus getOne(@RequestBody Menus menus) {
return menusService.getOne(menus);
}
@PostMapping("/save")
@ApiOperation(value = "新增或編輯", notes = "菜單表")
public boolean save(@RequestBody Menus menus) {
return menusService.saveOrUpdate(menus);
}
@PostMapping("/delete")
@ApiOperation(value = "刪除", notes = "菜單表")
public boolean delete(@RequestBody Menus menus) {
return menusService.delete(menus);
}
}
5.3 創(chuàng)建菜單表對(duì)應(yīng)的service
/**
* @author yinfeng
* @since 2022年3月12日 下午9:40:48
* @description 菜單表
* @TableName menus
*/
public interface MenusService extends IService<Menus> {
/**
* 查詢列表
*
* @param vo vo
* @return IPage<Menus>
*/
IPage<Menus> list(Menus vo);
/**
* 單個(gè)查詢
*
* @param vo vo
* @return Menus
*/
Menus getOne(Menus vo);
/**
* 保存
*
* @param vo vo
* @return 是否保存成功
*/
@Override
boolean saveOrUpdate(Menus vo);
/**
* 刪除
*
* @param vo vo
* @return 是否刪除成功
*/
boolean delete(Menus vo);
}
/**
* @author yinfeng
* @since 2022年3月12日 下午9:40:48
* @description 菜單表
* @TableName menus
*/
@Service
public class MenusServiceImpl extends ServiceImpl<MenusMapper, Menus>
implements MenusService{
@Override
public IPage<Menus> list(Menus vo){
final QueryWrapper<Menus> wrapper = new QueryWrapper<>();
wrapper.eq(ObjectUtils.isNotEmpty(vo.getId()), "id", vo.getId());
return super.page(new Page<>(vo.getCurrentPage(), vo.getPageSize()), wrapper);
}
@Override
public Menus getOne(Menus vo){
final QueryWrapper<Menus> wrapper = new QueryWrapper<>();
wrapper.eq(ObjectUtils.allNotNull(vo.getId()), "id", vo.getId());
return super.getOne(wrapper);
}
@Override
public boolean saveOrUpdate(Menus vo) {
return super.saveOrUpdate(vo);
}
@Override
public boolean delete(Menus vo) {
final QueryWrapper<Menus> wrapper = new QueryWrapper<>();
wrapper.eq(ObjectUtils.allNotNull(vo.getId()), "id", vo.getId());
return super.remove(wrapper);
}
}
5.3 創(chuàng)建菜單表對(duì)應(yīng)的mapper,相當(dāng)于直接操作數(shù)據(jù)庫(kù)的類(lèi)
/**
* @author yinfeng
* @since 2022年3月12日 下午9:40:48
* @description 菜單表
* @TableName menus
*/
@Mapper
public interface MenusMapper extends BaseMapper<Menus> {
}
由于使用mybatis plus框架,幫我們簡(jiǎn)化了很多簡(jiǎn)單的增刪改查,所以這里的service和mapper代碼就寫(xiě)得很清爽,但也可實(shí)現(xiàn)咱們的功能
6、接口測(cè)試
6.1 啟動(dòng)項(xiàng)目
6.2 通過(guò)knife4j測(cè)試接口
- 在瀏覽器打開(kāi)測(cè)試地址
http://127.0.0.1:8888/doc.html#/home
- 測(cè)試列表接口
curl -X POST -H "Accept:*/*" -H "Content-Type:application/json" -d "{\"currentPage\":1,\"pageSize\":20}" "http://127.0.0.1:8888/menus/list"
-
測(cè)試新增接口
在這里插入圖片描述
curl -X POST -H "Accept:*/*" -H "Content-Type:application/json" -d "{\"createTime\":\"2021-10-03 15:58:38\",\"level\":2,\"name\":\"用戶管理\",\"note\":\"用戶管理操作\",\"updateTime\":\"2021-10-03 15:58:38\"}" "http://127.0.0.1:8888/menus/save"
查看是否新增成功
-
測(cè)試詳情接口
在這里插入圖片描述
curl -X POST -H "Accept:*/*" -H "Content-Type:application/json" -d "{\"id\":1502651873142775800}" "http://127.0.0.1:8888/menus/getOne"
-
測(cè)試刪除接口
在這里插入圖片描述
curl -X POST -H "Accept:*/*" -H "Content-Type:application/json" -d "{\"id\":1502651873142775800}" "http://127.0.0.1:8888/menus/delete"
查看是否刪除成功
7、源碼地址
https://gitee.com/yinfeng-code/test.git
8、總結(jié)
這篇只是springboot入門(mén)項(xiàng)目,后面咱們可根據(jù)該項(xiàng)目逐步開(kāi)發(fā)更多高深的企業(yè)級(jí)功能,包括starter的封裝、數(shù)據(jù)操作變更日志、響應(yīng)體包裝等,歡迎老鐵們追更。
肝文不易,最后希望老鐵們給波三連(==點(diǎn)贊、收藏、評(píng)論==)加關(guān)注,非常感謝大家支持~~