1、springboot简介

特征

2、新建springboot web项目

按以下步骤依次操作
还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP
还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP
还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP
初始化项目完整的结构
还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP

3、基本配置

3.1 引入相关依赖

mysql连接依赖

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

mybatis-plus

特性

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>

knife4j

<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: 8888
spring:
  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

还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP

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("隐风 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();
        // 加入分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
        return interceptor;
    }
}

4、创建测试表

4.1 连接数据库

  1. 创建数据源
    还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP

  2. 配置连接信息
    还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP

  3. 执行建表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='菜单表';

还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP

  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);

还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP
还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP

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
 */
@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 创建菜单表对应的mapper,相当于直接操作数据库的类

/**
* @author yinfeng
* @since 2022年3月12日 下午9:40:48
* @description 菜单表
* @TableName menus
*/
@Mapper
public interface MenusMapper extends BaseMapper<Menus> {
}

6、接口测试

6.1 启动项目

还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP

6.2 通过knife4j测试接口

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

还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP

  1. 测试列表接口

还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP

curl -X POST -H  "Accept:*/*" -H  "Content-Type:application/json" -d "{\"currentPage\":1,\"pageSize\":20}" "http://127.0.0.1:8888/menus/list"
  1. 测试新增接口
    还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP
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"

查看是否新增成功
还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP

  1. 测试详情接口
    还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP
curl -X POST -H  "Accept:*/*" -H  "Content-Type:application/json" -d "{\"id\":1502651873142775800}" "http://127.0.0.1:8888/menus/getOne"
  1. 测试删除接口
    还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP
curl -X POST -H  "Accept:*/*" -H  "Content-Type:application/json" -d "{\"id\":1502651873142775800}" "http://127.0.0.1:8888/menus/delete"

查看是否删除成功
还不会用springboot写接口?快看这里,手把手操作,一发入魂~-LMLPHP

7、源码地址

https://gitee.com/yinfeng-code/test.git

8、总结

肝文不易,最后希望老铁们给波三连()加关注,非常感谢大家支持~~

03-16 22:05