项目引入Swagger及使用姿势

时间:2020-05-14 18:49:02   收藏:0   阅读:262

1.导入pom依赖

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
     <groupId>com.github.xiaoymin</groupId>
     <artifactId>knife4j-spring-boot-starter</artifactId>
     <version>2.0.2</version>
</dependency>

2.添加swagger配置类

package com.demo.config;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
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;

import java.util.HashSet;

/**
 * <p>
 * swagger页面展示的配置
 * </p>
 *
 * @author Toby
 * @since 2020/5/13
 */
@Configuration
@EnableSwagger2
@EnableKnife4j
public class Swagger2Configuration {

    @Bean
    public Docket createRestApi() {
        HashSet<String> contentType = new HashSet<>(1);
        contentType.add("application/json");
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .consumes(contentType)
                .produces(contentType)
                .select()
            	// 扫描包路径
                .apis(RequestHandlerSelectors.basePackage("com.demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("xxx-api文档")
                .description("xxx-xx模块api文档")
                .version("1.0")
                .contact(new Contact("xxx项目组","","xxxx@xxx.com"))
                .build();
    }
    

}

:basePackage要改为项目对应的controller目录路径,使用增强功能的话,需要在配置类上加@EnableKnife4j注解,并且在UI界面的个性化设置中开启增强功能。具体增强功能请移步至最后自行查看文档

3.查看UI界面

启动项目后,在浏览器输入http://${host}??{port}/doc.html

4.项目中可能会用到的增强功能

4.注意事项

5.文档地址

knife4j使用教程:https://doc.xiaominfo.com/knife4j/

GitHub地址:https://github.com/xiaoymin/swagger-bootstrap-ui

原文:https://www.cnblogs.com/tobyhomels/p/12890521.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!