使用Swagger2构建 RESTful API文档

Spring Boot 实现Swagger 2

Spring Boot 集成 Swagger 2很简单,首先新建一个 SpringBoot 项目,这里就不重新创建项目,直接使用之前的rest 测试项目。然后引入依赖并做基础配置即可:

1、配置Swagger2的依赖

在pom.xml 配置文件中,增加Swagger 2 的相关依赖,具体如下:

<!-- 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>

2、创建Swagger 2配置类

在com.weiz.config 包中,增加Swagger 2 的配置类,SwaggerConfig 类,具体代码如下:

package com.weiz.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
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 Swagger2Config implements WebMvcConfigurer {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.weiz.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("Spring Boot相关文章请关注:https://www.cnblogs.com/zhangweizhong")
                .termsOfServiceUrl("https://www.cnblogs.com/zhangweizhong")
                .contact("架构师精进")
                .version("1.0")
                .build();
    }

    /**
     *  swagger增加url映射
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

https://www.cnblogs.com/zhangweizhong/p/13185919.html

故乡明
原文地址:https://www.cnblogs.com/luweiweicode/p/15138055.html