SWAGGER快速使用指南

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yangyongdehao30/article/details/80579471


版本

作者

描述

日期

V1.0

yy

基于公司现有项目的swagger引入

2018-6-5 09:21:02

扫描二维码关注公众号,回复: 4061070 查看本文章

1      Swagger简介

Swagger是一款让程序自动生成API的开发插件。样式、内容等均可定制化,一般采取默认即可

2      Swagger引入

Java项目通常基于spring,spring也提供了相关中间件和swagger进行集成,使我们用起来更简单。下面则是不同的Spring版本引入swagger的方式

2.1  基于Springboot

1.在pom中引入:

<dependency>

           <groupId>io.springfox</groupId>

           <artifactId>springfox-swagger2</artifactId>

           <version>2.6.1</version>

        </dependency>

       <dependency>

           <groupId>io.springfox</groupId>

           <artifactId>springfox-swagger-ui</artifactId>

           <version>2.6.1</version>

       </dependency>

2.引入config

将这两个文件copy进工程中,能扫描到即可

package com.jinhuhang.settlement.plugins;

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.jinhuhang.settlement.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("settlement api文档")
                .description("settlement api文档 测试环境 ")
                .termsOfServiceUrl("")
                .version("1.0")
                .build();
    }
}
package com.jinhuhang.settlement.plugins;

import java.nio.charset.Charset;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MvcConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("index.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/");

    }   
    
    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(
                Charset.forName("UTF-8"));
        return converter;
    }

    @Override
    public void configureMessageConverters(
            List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        converters.add(responseBodyConverter());
    }

    @Override
    public void configureContentNegotiation(
            ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false);
    }
}


MvcConfiguration重点:解析jar包中的视图

3.打开 http://ip:port/项目名/swagger-ui.html

2.2  基于springmvc

1.maven依赖

<!-- 构建Restful API -->

<dependency>

   <groupId>io.springfox</groupId>

   <artifactId>springfox-swagger2</artifactId>

   <version>2.6.0</version>

</dependency>

<dependency>

   <groupId>io.springfox</groupId>

   <artifactId>springfox-swagger-ui</artifactId>

   <version>2.6.0</version>

</dependency>

2.Swagger配置文件

copy文件至可扫描路径

package com.custom.web.swagger;

import com.google.common.base.Predicate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
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.List;

import static com.google.common.base.Predicates.or;
import static com.google.common.collect.Lists.newArrayList;
import static springfox.documentation.builders.PathSelectors.regex;

@Configuration    // 配置注解,自动在本类上下文加载一些环境变量信息
@EnableSwagger2   // 使swagger2生效
@EnableWebMvc
@ComponentScan(basePackages = {"com.custom.web"})  //需要扫描的包路径
public class SwaggerConfig extends WebMvcConfigurationSupport {

    @Bean
    public Docket swaggerSpringMvcPlugin() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("business-api")
                .select()   // 选择那些路径和api会生成document
.apis(RequestHandlerSelectors.basePackage("com.custom.web"))
                .paths(paths())
                //.apis(RequestHandlerSelectors.any())  // 对所有api进行监控
                //.paths(PathSelectors.any())   // 对所有路径进行监控
.build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    private Predicate<String> paths() {
        return or(regex("/person.*"));
    }

    private List<ApiKey> securitySchemes() {
        return newArrayList(
                new ApiKey("clientId", "客户端ID", "header"),
                new ApiKey("clientSecret", "客户端秘钥", "header"),
                new ApiKey("accessToken", "客户端访问标识", "header"));
    }

    private List<SecurityContext> securityContexts() {
        return newArrayList(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(PathSelectors.regex("/*.*"))
                        .build()
        );
    }

    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return newArrayList(
                new SecurityReference("clientId", authorizationScopes),
                new SecurityReference("clientSecret", authorizationScopes),
                new SecurityReference("accessToken", authorizationScopes));
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring 中使用Swagger2构建RESTful API")
                .termsOfServiceUrl("")
                .description("此API提供接口调用")
                .version("2.0").build();
    }
}

要修改的点如下图:

3.web.xml配置说明

<servlet>

   <servlet-name>dispatcher</servlet-name>

   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

   <init-param>

       <param-name>contextConfigLocation</param-name>

       <param-value>classpath*:/spring-mvc.xml</param-value>

   </init-param>

   <load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

   <servlet-name>dispatcher</servlet-name>

   <url-pattern>*.do</url-pattern>

</servlet-mapping>

<servlet-mapping>

   <servlet-name>dispatcher</servlet-name>

   <url-pattern>/v2/api-docs</url-pattern>

</servlet-mapping>

说明:Springmvc前端控制器扫描路径增加“/v2/api-docs”,用于扫描Swagger的 /v2/api-docs,否则/v2/api-docs无法生效。

4.spring-mvc.xml 增加自动扫描Swagger

<!-- 使用 Swagger Restful API文档时,添加此注解-->

<mvc:default-servlet-handler />

<mvc:annotation-driven/>

或者

<mvc:resourceslocation="classpath:/META-INF/resources/"mapping="swagger-ui.html"/>

<mvc:resourceslocation="classpath:/META-INF/resources/webjars/"mapping="/webjars/**"/>

5.访问:http://IP:port/{context-path}/swagger-ui.html 

3      推荐使用参数

接口api为非业务代码,不建议代码占用太多篇幅。在这里只推荐使用一个标签,这个标签可以代替掉接口上的注释

参数

解释

@ApiOperation

接口描述(描述接口是干嘛的,对参数进行说明)

4      常用其他参数

参数

解释

@ApiOperation()

接口描述

@ApiParam()

字段描述

@ApiModel()

类描述(参数是实体类的情况)

@ApiModelProperty()

类字段描述(参数是实体类的情况)

@ApiIgnore()

类和方法(废弃的方法使用,代表不生成api)

5      效果与说明

5.1  效果1:

上图为添加@ApiOperation()的效果图

1>@ApiOperation()中的内容(接口说明)

2>自动生成的返回值(rest接口通常最简洁模式:

        {code:”是否成功 10”,”

msg”:”消息,失败时显示原因”,

”model”:”返回的内容,为Object类型,根据业务自定义

}

3>自动生成的参数类型

5.2  效果2

在字段上添加@ApiParam标签后的效果

代码片段如下:

该方式当字段比较多时候,controller方法入参显得过于臃肿,字段较多时可将参数描述放入ApiOperation中

5.3  效果3

当参数为实体类的情况,点击图中标记 即可赋值到左边文本域。直接进行编辑即可发送情况。

6      常用接口规范

通常入参根据具体业务规范,返回参数规范如下:

字段

类型

描述

code

Int

是否成功 1是0否

msg

String

消息描述

Model

Object

任意类型参数

{“code”:“是否成功 1是0否”,

“msg”:“消息,失败时显示原因”,

“model”:“返回的内容,为Object类型,根据业务自定义”

}

7      参注

Swagger官网: https://swagger.io/

同类型框架:https://spring.io/projects/spring-restdocs


猜你喜欢

转载自blog.csdn.net/yangyongdehao30/article/details/80579471