Swagger2 配置在线接口文档

swagger2的使用优点:

  1、有时候接口太多,维护力度太多;swagger减少了这些麻烦。

  2、直接在线测试接口

swagger2的依赖配置步骤:

1、添加maven依赖:

      <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.8</version>
        </dependency>

  2、添加 SwaggerConfig.java 启动配置

package com.ppfuns.auth.api.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.util.UriComponentsBuilder;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.paths.AbstractPathProvider;
import springfox.documentation.spring.web.paths.Paths;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

@Component
@Configuration
@EnableSwagger2
@EnableWebMvc
@ComponentScan("com.ppfuns.auth.api.controller")  //指定扫描的controller目录
public class SwaggerConfig {
//    @Value("${swagger.enable}")
    private boolean enableSwagger =true; //enableSwagger是多环境配置开关,一般生产环境中不想打开swagger的uil界面,就可以让其为false
    @Bean
    public Docket createAPI() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(enableSwagger)
                .forCodeGeneration(true)
                .pathProvider(new CustRelativePathProvider()) //重定义接口路径
                .select()
                .apis(RequestHandlerSelectors.any())
//                过滤生成链接
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/")
//                .globalResponseMessage(RequestMethod.GET, getResponseMessageList())
//                .globalResponseMessage(RequestMethod.POST, getResponseMessageList())
//                .globalResponseMessage(RequestMethod.PUT, getResponseMessageList())
//                .globalResponseMessage(RequestMethod.DELETE, getResponseMessageList())
                .apiInfo(apiInfo());
    }
   private List<ResponseMessage> getResponseMessageList(){ //定义response结果
       List<ResponseMessage> responseMessageList = new ArrayList<>();
       responseMessageList.add(new ResponseMessageBuilder().code(404).message("找不到资源").responseModel(new ModelRef("Error")).build());
       responseMessageList.add(new ResponseMessageBuilder().code(409).message("业务逻辑异常").responseModel(new ModelRef("Error")).build());
       responseMessageList.add(new ResponseMessageBuilder().code(422).message("参数校验异常").responseModel(new ModelRef("Error")).build());
       responseMessageList.add(new ResponseMessageBuilder().code(500).message("服务器内部错误").responseModel(new ModelRef("Error")).build());
       responseMessageList.add(new ResponseMessageBuilder().code(503).message("Hystrix异常").responseModel(new ModelRef("Error")).build());
       return responseMessageList;
   }
    private ApiInfo apiInfo() {
        Contact contact=new Contact("SunnJam","http://localhost:8888/","jiandq@88.com");
        ApiInfo apiInfo = new ApiInfoBuilder().
                license("Apache License Version 2.0").
                title("API接口").
                description("API SWAGGER 接口文档目录").
                contact(contact).
                version("1.0.0").build();

        return apiInfo;
    }
    /**
     *对接口路径进行规划和定义; 这里在项目中swagger测试时,接口路径以.json结尾
   **/
    public class CustRelativePathProvider extends AbstractPathProvider {
        public static final String ROOT = "/";

        @Override
        public String getOperationPath(String operationPath) {
            UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromPath("/");
            String uri = Paths.removeAdjacentForwardSlashes(uriComponentsBuilder.path(operationPath).build().toString());
            return operationPath + ".json";
        }

        @Override
        protected String applicationPath() {
            return ROOT;
        }

        @Override
        protected String getDocumentationPath() {
            return ROOT;
        }
    }

}

3、web配置(由于接口路径加了后缀,对swagger2的接口不做后缀处理)

<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/spring-mvc.xml
      </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.htm</url-pattern>
    <url-pattern>*.json</url-pattern>
    <url-pattern>*.xml</url-pattern>
    <url-pattern>*.m3u8</url-pattern>
    <url-pattern>/v2/api-docs</url-pattern>
    <url-pattern>/swagger-resources/configuration/ui</url-pattern>
    <url-pattern>/swagger-resources</url-pattern>
    <url-pattern>/swagger-resources/configuration/security</url-pattern>
    <url-pattern>/swagger-resources/**</url-pattern>

4、配置静态访问路径(pring-mvc.xml)

<!--这里定义一个Swagger的bean 由于我的项目没对com.ppfuns.auth.api.config目录做context:component-scan的扫描 -->
<bean class="com.ppfuns.auth.api.config.SwaggerConfig" />
	<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
	<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />

5、swagger访问:

http://localhost:8888/swagger-ui.html

http://localhost:8888/v2/api-docs

上述已完成对swagger2接口的配置;如果想使用swagger的html和pdf文件的生成:https://blog.csdn.net/jiandequn/article/details/94720045

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>