Spring MVC中使用 Swagger2 構建Restful API


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配置文件

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("http://blog.csdn.net/yangshijin1988")
                .description("此API提供接口調用")
                .license("License Version 2.0")
                .licenseUrl("http://blog.csdn.net/yangshijin1988")
                .version("2.0").build();
    }
}

3.Controller中使用注解添加API文檔

package com.custom.web.index.controller;

importcom.custom.web.index.entity.Person;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by Administrator on 2017/4/8.
 */
@Controller
@RequestMapping("/person")
@Api(tags="個人業務")
public class PersonController {

    @RequestMapping(value="/getPerson",method= RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "個人信息", produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody Person getPersons() {
        Person person = new Person();
        person.setFirstName("fname");
        person.setLastName("lname");
        person.setAge(37);
        person.setDeptName("dept");
        return person;
    }
}

4.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無法生效。
 
5.spring-mvc.xml 增加自動掃描Swagger
<!-- 使用 Swagger Restful API文檔時,添加此注解 -->
<mvc:default-servlet-handler />
<mvc:annotation-driven/>
或者
<mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/>
<mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>
 

6.效果展示

Restful API 訪問路徑:  

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

 
 
 
7、使用Swagger UI模板
可在Swagger官網下載。地址:https://github.com/swagger-api/swagger-ui。
下載完成后將swagger-ui下的dist目錄下的模板放入項目中,如在項目web-app下新建swagger放swagger-ui模板。
在spring-mvc中配置swagger文件夾自動過濾。
<mvc:resources mapping="/swagger/**" location="/swagger/" cache-period="31556926" />
將index.html或swagger-ui.html文件js中的url換成url = "/v2/api-docs?group=business-api";
 

 

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM