springboot集成swagger+knife4j

官网:https://swagger.io/

swagger介绍:

Swagger 是一款RESTFUL接口的、基于YAML、JSON语言的文档在线自动生成、代码自动生成的工具。
RestFul Api 文档在线自动生成工具,直接运行,可以在线测试API接口,支持多种语言:(Java,Php…)。

支持 API 自动生成同步的在线文档:使用 Swagger 后可以直接通过代码生成文档,不再需要自己手动编写接口文档了,提供 Web 页面在线测试 API,wagger 生成的文档还支持在线测试。参数和格式都定好了,直接在界面上输入参数对应的值即可在线测试接口。

集成swagger:

一、引入相关依赖:

        <!-- swagger -->
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

二、配置
创建SwaggerConfig类

这里的配置比较简单,swagger很多选项配置看自己需要。如果我们的项目有多个组,只需要创建多个Docket即可。这时候扫描的包换成每个组的包路径。

@Configuration //声明该类为配置类
@EnableSwagger2 //声明启动Swagger2
public class SwaggerConfig {
    @Bean
    public Docket customDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.consumerdemo"))//扫描的包路径
                .build();
    }

    // 构建 api文档的详细信息函数
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("测试")//文档说明(页面标题)
                .version("1.0.0")//文档版本说明
                .description("系统API描述")
                .contact(new Contact("创建人姓名","http://XXX",""))// 创建人
                .build();
    }
}

三、可以新建一个Controller测试

@RestController
@Component
@Api(tags = "测试swagger",description = "描述")
public class TestSwaggerController {

    @ApiOperation(value="通过id进行测试",notes = "adsad")
    @GetMapping("testSwagger")
    @ApiImplicitParam(name = "id",value = "测试的id",dataType = "String")
    public String testSwagger(String id){
        System.out.println("id===="+id);
        return "测试测试";
    }
}

注释:
springboot集成swagger+knife4j_第1张图片
四、访问页面

访问格式:http://IP地址或域名:端口/应用名称/swagger-ui.html

springboot集成swagger+knife4j_第2张图片
五、knife4j 简单使用

knife4j完全遵循了springfox-swagger中的使用方式,并在此基础上做了增强功能,如果用过Swagger,可以无缝切换到knife4j。

1、在pom.xml中增加knife4j的相关依赖

        <!--整合Knife4j-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>2.0.4</version>
        </dependency>

2、在SwaggerConfig中增加一个@EnableKnife4j注解,该注解可以开启Knife4j的增强功能。
springboot集成swagger+knife4j_第3张图片
3、重新启动

访问格式:http://IP地址或域名:端口/应用名称/doc.html

你可能感兴趣的:(java)