Swagger的说明、配置

Swagger的说明、配置


一、什么是Swagger?

官方介绍:Swagger是一个规范且完整的框架,提供描述、生产、消费和可视化Restful Web Service。
专业角度:Swagger是由庞大工具集合支撑的形式化规范。这个集合涵盖了从终端用户接口、底层代码库到商业Api管理的方方面面。

二、配置

1.开发环境介绍

  • jdk 1.8
  • swagger 2.8.0

2.在pom.xml文件中添加Swagger相关依赖

    <!-- Swagger2 -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.8.0</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.8.0</version>
    </dependency>

3.自定义对Swagger的配置

对于Swagger的配置,其实可以自定义一个与Swagger相关的config类,可以通过Java编码的实现配置,代码如下:

package com.allqj.learner_autonomy.base.config;

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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.allqj.learner_autonomy"))
                .paths(PathSelectors.any())
                .build();
    }
    
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("练习项目")
                .description("练习各种技术")
                .termsOfServiceUrl("localhost")
                .version("1.0")
                .build();
    }
}

4.配置需要解析的接口方法

package com.allqj.learner_autonomy.base.controller;

import com.allqj.learner_autonomy.base.service.TestService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(value = "测试Swagger", description = "练习Swagger的使用")
@RestController
public class TestController {

    @Autowired
    private TestService testService;
    
    @ApiOperation(value = "删除用户信息", notes = "删除用户")
    @PostMapping("/deleteUser")
    public void deleteUser(Integer id) {
        testService.deleteUser(id);
    }

}

5.运行项目,访问URL
localhost:8080/swagger-ui.html

访问成功!

猜你喜欢

转载自blog.csdn.net/qq_42875667/article/details/86562422
今日推荐