1、springboot简介

Spring Boot 能够轻松创立能够“间接运行”的独立的、生产级的基于 Spring 的应用程序。

特色

创立独立的 Spring 应用程序

间接嵌入 Tomcat、Jetty 或 Undertow(无需部署 WAR 文件)

提供强健的“入门”依赖项以简化您的构建配置

尽可能主动配置 Spring 和第三方中间件

提供生产就绪性能,例如指标、健康检查和内部化配置

齐全无需代码生成,无需 XML 配置

2、新建springboot web我的项目

按以下步骤顺次操作



初始化我的项目残缺的构造

3、根本配置

3.1 引入相干依赖

mysql连贯依赖

<dependency>    <groupId>mysql</groupId>    <artifactId>mysql-connector-java</artifactId></dependency>

mybatis-plus

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的加强工具,在 MyBatis 的根底上只做加强不做扭转,为简化开发、提高效率而生。

个性

无侵入:只做加强不做扭转,引入它不会对现有工程产生影响,如丝般顺滑
损耗小:启动即会主动注入根本 CURD,性能根本无损耗,间接面向对象操作
弱小的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过大量配置即可实现单表大部分 CRUD 操作,更有弱小的条件结构器,满足各类应用需要
反对 Lambda 模式调用:通过 Lambda 表达式,不便的编写各类查问条件,无需再放心字段写错
反对主键主动生成:反对多达 4 种主键策略(内含分布式惟一 ID 生成器 - Sequence),可自在配置,完满解决主键问题
反对 ActiveRecord 模式:反对 ActiveRecord 模式调用,实体类只需继承 Model 类即可进行弱小的 CRUD 操作
反对自定义全局通用操作:反对全局通用办法注入( Write once, use anywhere )
内置代码生成器:采纳代码或者 Maven 插件可疾速生成 Mapper 、 Model 、 Service 、 Controller 层代码,反对模板引擎,更有超多自定义配置等您来应用
内置分页插件:基于 MyBatis 物理分页,开发者无需关怀具体操作,配置好插件之后,写分页等同于一般 List 查问
分页插件反对多种数据库:反对 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
内置性能剖析插件:可输入 SQL 语句以及其执行工夫,倡议开发测试时启用该性能,能疾速揪出慢查问
内置全局拦挡插件:提供全表 delete 、 update 操作智能剖析阻断,也可自定义拦挡规定,预防误操作
<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是一个纯swagger-ui的ui皮肤我的项目。
一开始我的项目初衷是为了写一个加强版本的swagger的前端ui,然而随着我的项目的倒退,面对越来越多的个性化需要,不得不编写后端Java代码以满足新的需要,在swagger-bootstrap-ui的1.8.5~1.9.6版本之间,采纳的是后端Java代码和Ui都混合在一个Jar包外面的形式提供给开发者应用.这种形式虽说对于集成swagger来说很不便,只须要引入jar包即可,然而在微服务架构下显得有些臃肿。
因而,我的项目正式更名为knife4j,取名knife4j是心愿她能像一把匕首一样玲珑,轻量,并且性能强悍,更名也是心愿把她做成一个为Swagger接口文档服务的通用性解决方案,不仅仅只是专一于前端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:  # 服务端口  port: 8888spring:  application:    name: yinfeng-test  # 数据库相干配置  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@EnableSwagger2public class Knife4jConfig {    @Bean    public Docket buildDocket() {        return new Docket(DocumentationType.SWAGGER_2)                .apiInfo(new ApiInfoBuilder().title("隐风 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 */@Configurationpublic 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 */@Configurationpublic class MybatisPlusConfig {    @Bean    public MybatisPlusInterceptor mybatisPlusInterceptor() {        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();        // 退出分页插件        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));        return interceptor;    }}

4、创立测试表

4.1 连贯数据库

能够通过idea的数据库工具间接连贯数据库
  1. 创立数据源

  1. 配置连贯信息

  1. 执行建表sql
CREATE TABLE `menus` (  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '菜单id',  `level` int(11) NOT NULL DEFAULT '1' COMMENT '菜单等级',  `name` varchar(11) NOT NULL DEFAULT '' COMMENT '菜单名',  `note` varchar(500) DEFAULT NULL COMMENT '备注',  `create_time` datetime NOT NULL COMMENT '创立工夫',  `update_time` datetime NOT NULL COMMENT '更新工夫',  `deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT '删除标记',  PRIMARY KEY (`id`) USING BTREE,  UNIQUE KEY `menus_id_uindex` (`id`) USING BTREE) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='菜单表';

  1. 创立测试数据
INSERT INTO `menus` (`id`, `level`, `name`, `update_time`, `note`, `create_time`, `deleted`) VALUES (1, 1, '首页', '2021-08-22 13:44:51', '首页', '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、接口开发

5.1 创立菜单表对应的实体类

/** * @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;    /**     * 菜单等级     */    @TableField("level")    @ApiModelProperty(value = "菜单等级", example = "")    private Integer level;    /**     * 菜单名     */    @TableField("name")    @ApiModelProperty(value = "菜单名", example = "")    private String name;    /**     * 备注     */    @TableField("note")    @ApiModelProperty(value = "备注", example = "")    private String note;    /**     * 创立工夫     */    @TableField(value = "create_time", fill = FieldFill.INSERT)    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")    @ApiModelProperty(value = "创立工夫", example = "")    private Date createTime;    /**     * 更新工夫     */    @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")    @ApiModelProperty(value = "更新工夫", example = "")    private Date updateTime;    /**     * 删除标记     */    @TableField("deleted")    @TableLogic    @JsonIgnore    @ApiModelProperty(value = "删除标记", example = "")    private Integer deleted;    /**     * 当前页     */    @ApiModelProperty(value = "当前页", example = "1")    @TableField(exist = false)    private Integer currentPage;    /**     * 分页页数     */    @ApiModelProperty(value = "分页页数", example = "20")    @TableField(exist = false)    private Integer pageSize;}

5.2 创立菜单表对应的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 = "单个查问", 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 创立菜单表对应的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);    /**     * 单个查问     *     * @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 */@Servicepublic 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 创立菜单表对应的mapper,相当于间接操作数据库的类

/*** @author yinfeng* @since 2022年3月12日 下午9:40:48* @description 菜单表* @TableName menus*/@Mapperpublic interface MenusMapper extends BaseMapper<Menus> {}
因为应用mybatis plus框架,帮咱们简化了很多简略的增删改查,所以这里的service和mapper代码就写得很清新,但也可实现咱们的性能

6、接口测试

6.1 启动我的项目

6.2 通过knife4j测试接口

  1. 在浏览器关上测试地址
http://127.0.0.1:8888/doc.html#/home

  1. 测试列表接口

curl -X POST -H  "Accept:*/*" -H  "Content-Type:application/json" -d "{\"currentPage\":1,\"pageSize\":20}" "http://127.0.0.1:8888/menus/list"
  1. 测试新增接口

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"

查看是否新增胜利

  1. 测试详情接口

curl -X POST -H  "Accept:*/*" -H  "Content-Type:application/json" -d "{\"id\":1502651873142775800}" "http://127.0.0.1:8888/menus/getOne"
  1. 测试删除接口

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、总结

这篇只是springboot入门我的项目,前面咱们可依据该我的项目逐渐开发更多浅近的企业级性能,包含starter的封装、数据操作变更日志、响应体包装等,欢送老铁们追更。

肝文不易,最初心愿老铁们给波三连(==点赞、珍藏、评论==)加关注,非常感谢大家反对~~