---
title: "springmvc集成swagger-ui"
author: "lp895876294"
date: "2016-01-06T09:00:03Z"
tags: []
categories: ["开源软件"]
slug: "springmvc-swagger-ui"
draft: false
lastmod: "2016-01-06T09:01:53Z"
id: 2268837
url: "https://lpyyn.iteye.com/blog/2268837"
---

- 引入基于maven的swagger依赖
  
  ```
  <dependency>
              <groupId>com.mangofactory</groupId>
              <artifactId>swagger-springmvc</artifactId>
              <version>1.0.2</version>
          </dependency>
  
          <dependency>
              <groupId>com.fasterxml.jackson.core</groupId>
              <artifactId>jackson-annotations</artifactId>
              <version>2.3.1</version>
          </dependency>
  
          <dependency>
              <groupId>com.fasterxml.jackson.core</groupId>
              <artifactId>jackson-databind</artifactId>
              <version>2.3.1</version>
          </dependency>
  
          <dependency>
              <groupId>com.fasterxml.jackson.core</groupId>
              <artifactId>jackson-core</artifactId>
              <version>2.3.1</version>
          </dependency>
  ```
- 项目是基于Spring-boot搭建，以注解的方式引入swagger-springmvc配置。
  
  ```
  import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
  import com.mangofactory.swagger.models.dto.ApiInfo;
  import com.mangofactory.swagger.plugin.EnableSwagger;
  import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
  import org.springframework.context.annotation.Bean;
  import org.springframework.context.annotation.Configuration;
  
  @Configuration
  @EnableSwagger
  public class SwaggerConfig {
  
      @Bean
      public SwaggerSpringMvcPlugin customImplementation(SpringSwaggerConfig springSwaggerConfig) {
          SwaggerSpringMvcPlugin swaggerSpringMvcPlugin = new SwaggerSpringMvcPlugin(springSwaggerConfig) ;
          //rest地址是以regex的方式匹配
          swaggerSpringMvcPlugin.apiInfo(apiInfo()).includePatterns("/api/.*" ,
                  "/ticket/.*" , "/dictionary/.*" , "/oss/.*");
  
          return swaggerSpringMvcPlugin ;
      }
  
      public ApiInfo apiInfo(){
          ApiInfo apiInfo = new ApiInfo("APP接口" ,
                  "如果没有特殊说明，所有接口返回的数据格式为JSON格式，JSON模板为：{ \"success\":true或false , \"data\":{数据} }" ,
                  "" , "" , "" , "") ;
  
          return apiInfo ;
      }
  }
  ```
  
   至此，项目中swagger-springmvc配置完成。如果项目中进行了权限过滤，需要放开swagger对外提供的api接口，接口地址为/api-docs/\** ，并设置可以跨域访问。
- 集成swagger-ui 。 由swagger-ui的github地址下载发布的内容，swagger的github地址 ： https://github.com/swagger-api/swagger-ui 。
- 下载完成后将dist目录中的内容放到tomcat的webapps/ROOT目录下，修改index.html中http://petstore.swagger.io/v2/swagger.json 为 项目的/api-docs地址。

        部署完成之后，swagger-ui通过访问/api-docs地址获取rest接口地址。每个接口地址的详情则是通过访问/api-docs下的内置地址规则获取。

 

        问题：

- swagger-ui页面js存在bug，修改后的swagger-ui见附件。
- swagger-ui页面中接口地址即使用注解声明接口描述信息，在swagger-ui中也无中文说明。可能是配置的问题，留作继续学习。
- swagger-ui中接口测试，如果跨域访问接口仍有问题，留作继续学习。