2022-01-24 五.Swagger API文档

Swagger

配置

导包

3.0.0以下版本maven导入依赖:

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${springfox.version}</version>
</dependency>

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${springfox.version}</version>
</dependency>

3.0.0及以上版本可使用maven导入依赖:

 Swagger API文档 
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

编写配置类

配置类

package com.zsl.config.swagger;


import com.google.common.collect.Lists;
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.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Collections;
import java.util.List;


/**
 * @Author zsl
 * @Date 2022/1/21 11:16
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig  {
    private final SwaggerProperties swaggerProperties;

    public SwaggerConfig(SwaggerProperties swaggerProperties) {
        this.swaggerProperties = swaggerProperties;
    }

    @Bean
    public Docket petApi() {
        return new Docket(DocumentationType.SWAGGER_2)

                // api文档信息
                .apiInfo(apiInfo())

                // 分组名称
                .groupName(swaggerProperties.getApplicationVersion())

                // 定义是否开启swagger,false为关闭,可以通过yaml配置变量控制
                .enable(swaggerProperties.getEnable())

                // 选择那些接口作为swagger的doc发布
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.zsl.controller"))    // api路径
                .paths(PathSelectors.any()) // 路径匹配
                .build()

                // 授权信息全局应用
                .securityContexts(securityContexts())

                // 授权信息设置,必要的header token等认证信息
                .securitySchemes(apiKeys());
    }

    /**
     * API 页面上半部分展示信息
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(swaggerProperties.getApplicationName() + " 登录模块")
                .description(swaggerProperties.getApplicationDescription())
                .version("Application Version: " + swaggerProperties.getApplicationVersion())
                .build();
    }

    /**
     * 设置授权信息
     */
    private List<SecurityScheme> apiKeys() {
        return Lists.newArrayList(new ApiKey("Bearer Token", "Authorization", "header"));
    }

    /**
     * 授权信息全局应用
     */
    private List<SecurityContext> securityContexts() {
        return Lists.newArrayList(SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex("/.*"))
                .build());
    }

    /**
     *
     */
    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Collections.singletonList(new SecurityReference("Bearer Token", authorizationScopes));
    }
}

资源类

package com.zsl.config.swagger;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @Author zsl
 * @Date 2022/1/23 14:40
 */
@Component
@ConfigurationProperties(prefix = "swagger")
public class SwaggerProperties {
    private Boolean enable; // 是否开启swagger
    private String applicationName; // 应用程序名称
    private String applicationVersion;  // 应用程序版本
    private String applicationDescription;  // 应用程序描述
    private String tryHost; //  接口调试地址

    public Boolean getEnable() {
        return enable;
    }

    public void setEnable(Boolean enable) {
        this.enable = enable;
    }

    public String getApplicationName() {
        return applicationName;
    }

    public void setApplicationName(String applicationName) {
        this.applicationName = applicationName;
    }

    public String getApplicationVersion() {
        return applicationVersion;
    }

    public void setApplicationVersion(String applicationVersion) {
        this.applicationVersion = applicationVersion;
    }

    public String getApplicationDescription() {
        return applicationDescription;
    }

    public void setApplicationDescription(String applicationDescription) {
        this.applicationDescription = applicationDescription;
    }

    public String getTryHost() {
        return tryHost;
    }

    public void setTryHost(String tryHost) {
        this.tryHost = tryHost;
    }
}

yaml

# ===== 自定义swagger配置 ===== #
swagger:
  enable: true
  try-host: http://localhost:${server.port}
  application-name: ${spring.application.name}
  application-description: 登录练习 整合swagger 2.9.2
  application-version: v0.0.1

mvc映射配置(可选)

/**
 * @Author zsl
 * @Date 2022/5/9 15:48
 * @Email 249269610@qq.com
 */
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(false)
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowedOrigins("*");
    }

    //添加swagger-ui.html映射
    @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/");
    }
    //指定swagger-ui.html为index
    @Override
    public void addViewControllers( ViewControllerRegistry registry ) {
        registry.addViewController( "/" ).setViewName( "redirect:/swagger-ui.html" );
        registry.setOrder( Ordered.HIGHEST_PRECEDENCE );
    }

}

注解

@Api

用在controller类,描述API接口

@ApiOperation

描述接口方法

@ApiModel

描述对象

@ApiModelProperty

描述对象属性

@ApiImplicitParams

描述接口参数

@ApiResponses

描述接口响应

@ApiIgnore

忽略接口方法

swagger-ui 访问url

3以下版本

url:http://ip:port/swagger-ui.html

3及以上版本

url:http://ip:port/swagger-ui/index.html

参考文章

官方文档

Swagger 3.0使用教程

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Swagger Maven Plugin是一个用于生成Swagger接口文档的Maven插件。它可以帮助开发人员在构建项目时自动生成Swagger规范的JSON或YAML文件,以便于API文档的管理和使用。 使用Swagger Maven Plugin生成接口文档swagger.json或swagger.yaml的步骤如下: 1. 在项目的pom.xml文件中添加Swagger Maven Plugin的依赖配置: ```xml <build> <plugins> <plugin> <groupId>com.github.kongchen</groupId> <artifactId>swagger-maven-plugin</artifactId> <version>3.1.8</version> <configuration> <!-- 配置Swagger文档的基本信息 --> <apiSources> <apiSource> <springmvc>true</springmvc> <locations>com.example.controller</locations> <basePath>/api</basePath> <info> <title>API文档</title> <version>1.0.0</version> <description>API接口文档</description> <termsOfServiceUrl>http://example.com/terms-of-service</termsOfServiceUrl> <contact> <email>[email protected]</email> </contact> <license> <name>Apache 2.0</name> <url>http://www.apache.org/licenses/LICENSE-2.0.html</url> </license> </info> </apiSource> </apiSources> </configuration> <executions> <execution> <phase>compile</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> </plugin> </plugins> </build> ``` 2. 在项目根目录下执行以下命令生成Swagger接口文档: ``` mvn compile swagger:generate ``` 3. 执行完上述命令后,Swagger Maven Plugin会根据配置的信息扫描项目中的接口,并生成Swagger规范的JSON或YAML文件。生成的文件默认保存在项目的target目录下的swagger目录中。 生成的Swagger接口文档可以通过访问http://localhost:8080/api/swagger-ui.html(假设项目部署在本地的8080端口)来查看和测试API接口。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值