SpringBoot集成 Swagger2

1 篇文章 0 订阅
1 篇文章 0 订阅

Swagger2 作为一个规范和完整的框架,可以用于生成、描述、调用和可视化 RESTful 风格的 Web 服务:
1、接口文档在线自动生成,文档随接口变动实时更新,节省维护成本
2、支持在线接口测试,不依赖第三方工具

1、pom.xml 添加 Maven 依赖

        <!-- swagger2 配置 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.6</version>
        </dependency>

2、创建 Swagger2.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 *
 * @author Jeno<Jenolijun@aliyun.com>
 * @Date 2020/8/22
 *
 */
@Configuration
@EnableSwagger2
public class Swagger2 {

//    http://localhost:8080/swagger-ui.html     原路径
//    http://localhost:8080/doc.html     原路径

    //配置swagger2核心配置 docket
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)  //指定API类型为swagger2
                    .apiInfo(apiInfo())                 //用于定义API文档汇总信息
                    .select()
                    .apis(RequestHandlerSelectors
                    .basePackage("com.saimai.controller"))      //指定controller包
                    .paths(PathSelectors.any())             //所有controller
                    .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("电商平台接口API")               //文档标题
                .contact(new Contact("Jeno",
                        "https://www.guanlijun.cn",
                        "Jenolijun@aliyun.com"))    //联系人信息
                .description("商城提供的API文档")        //详细信息
                .version("1.0.1")                          //文档版本号
                .termsOfServiceUrl("https://www.guanlijun.cn")//网站地址
                .build();
    }
}

Swagger2.java 配置类的内容不多,配置完成后基本不会有大变动

3、API 接口编写

import com.saimai.enums.YesOrNo;
import com.saimai.pojo.Carousel;
import com.saimai.pojo.Category;
import com.saimai.pojo.vo.CategoryVO;
import com.saimai.pojo.vo.NewItemsVO;
import com.saimai.service.CarouselService;
import com.saimai.service.CategoryService;
import com.saimai.utils.SaiMaiJSONResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author Jeno<Jenolijun@aliyun.com>
 * @Date 2020/8/25
 */
@Api(value = "首页", tags = {"首页展示的相关接口"})
@RestController
@RequestMapping("index")
public class IndexContriller {

    @Autowired
    private CarouselService carouselService;

    @Autowired
    private CategoryService categoryService;


    final static Logger logger = LoggerFactory.getLogger(IndexContriller.class);

    @ApiOperation(value = "获取首页轮播图列表", notes = "获取首页轮播图列表", httpMethod = "GET")
    @GetMapping("/carousel")
    public SaiMaiJSONResult carousel() {
        List<Carousel> carousels = carouselService.queryAll(YesOrNo.YES.type);
        return SaiMaiJSONResult.ok(carousels);
    }

    /**
     * 首页分类展示需求:
     * 1. 第一次刷新主页查询大分类,渲染展示到首页
     * 2. 如果鼠标上移到大分类,则加载其子分类的内容,如果已经存在子分类,则不需要加载(懒加载)
     */
    @ApiOperation(value = "获取商品分类(一级分类)", notes = "获取商品分类(一级分类)", httpMethod = "GET")
    @GetMapping("/cats")
    public SaiMaiJSONResult cats() {
        List<Category> categorys = categoryService.queryAllRootLevelCat();
        return SaiMaiJSONResult.ok(categorys);
    }

    @ApiOperation(value = "获取商品子分类", notes = "获取商品子分类", httpMethod = "GET")
    @GetMapping("/subCat/{rootCatId}")
    public SaiMaiJSONResult subCat(
            @ApiParam(name = "rootCatId", value = "一级分类ID", required = true)
            @PathVariable Integer rootCatId) {
        if (rootCatId == null) {
            return SaiMaiJSONResult.errorMsg("分类不存在");
        }

        List<CategoryVO> list = categoryService.getSubCatList(rootCatId);
        return SaiMaiJSONResult.ok(list);
    }

    @ApiOperation(value = "查询每个一级分类下的最新6条数据", notes = "查询每个一级分类下的最新6条数据", httpMethod = "GET")
    @GetMapping("/sixNewItems/{rootCatId}")
    public SaiMaiJSONResult sixNewItems(
            @ApiParam(name = "rootCatId", value = "一级分类ID", required = true)
            @PathVariable Integer rootCatId) {
        if (rootCatId == null) {
            return SaiMaiJSONResult.errorMsg("分类不存在");
        }

        List<NewItemsVO> list = categoryService.getSixNewItemsLazy(rootCatId);
        return SaiMaiJSONResult.ok(list);
    }

}

Swagger 通过注解定制接口对外展示的信息,这些信息包括接口名、请求方法、参数、返回信息等。
主要注解有:
@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiImplicitParam:描述一个请求参数,可以配置参数的中文含义,还可以给参数设置默认值
@ApiImplicitParams:描述由多个 @ApiImplicitParam 注解的参数组成的请求参数列表
@ApiProperty:用对象接收参数时,描述对象的一个字段
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiError :发生错误返回的信息

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jeno LiJun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值