• 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";
     
     
     
  • 相关阅读:
    loglikelihood ratio 相似度
    实例详解机器学习如何解决问题
    【特征工程】特征选择与特征学习
    基于贝叶斯的文本分类实战
    转 :scikit-learn的GBDT工具进行特征选取。
    QT静态库和动态库的导出
    C#.NET为List加入扩展方法:获取唯一值
    caffe卷积层代码阅读笔记
    UVa 11300
    zoj 3882 Help Bob(zoj 2015年7月月赛)
  • 原文地址:https://www.cnblogs.com/exmyth/p/7183753.html
Copyright © 2020-2023  润新知