SpringMVC项目接入Springfox

一、简介

Springfox的前身是swagger-springmvc,是一个开源的API doc框架,可以将我们的Controller的方法以文档的形式展现。

二、接入

1、pom依赖

1)必要

<!--springfox依赖-->
<dependency>
    <groupId>com.mangofactory</groupId>
    <artifactId>swagger-springmvc</artifactId>
    <version>1.0.2</version>
</dependency>
<!--jackson依赖-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.2</version>
</dependency>
<!--静态页面依赖的webjar-->
<dependency>
    <groupId>org.webjars.bower</groupId>
    <artifactId>swagger-ui</artifactId>
    <version>2.1.8-M1</version>
</dependency>

2)如果项目依赖的Spring版本小于3.2.0.RELEASE则需要升级spring-web的依赖,以及guava的版本依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>3.2.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>15.0</version>
</dependency>

2、Springfox配置文件

SpringfoxConfig类

 /*
 * Copyright (c) 2015. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */



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.beans.factory.annotation.Autowired;
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.WebMvcConfigurerAdapter;

import java.io.File;

/**
 * 使用注解的方式来扫描API
 * 无需在Spring的xml配置文件来配置,由 @see @EnableWebMvc 代替
 * <p/>
 * <p> @author 刘新宇
 * <p/>
 * <p> @date 2015年4月26日 下午1:18:48
 * <p> @version 0.0.1
 */
@Configuration
@EnableWebMvc
@EnableSwagger
public class SpringfoxConfig extends WebMvcConfigurerAdapter {

    /**
     * Project Name
     */
    public static String PROJECT_NAME;

    static {
        String projectName = System.getProperty("user.dir");
        if (projectName.contains("hotel")) {
            int end = projectName.indexOf(File.separator, projectName.indexOf("hotel"));
            PROJECT_NAME = projectName.substring(projectName.lastIndexOf(File.separator, projectName.indexOf("hotel")) + 1, end == -1 ? projectName.length() : end);
        } else {
            PROJECT_NAME = "hotel-server";
        }
    }

    private SpringSwaggerConfig springSwaggerConfig;

    @Autowired
    public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
        this.springSwaggerConfig = springSwaggerConfig;
    }

    /**
     * 链式编程 来定制API样式
     * 后续会加上分组信息
     *
     * @return
     */
    @Bean
    public SwaggerSpringMvcPlugin customImplementation() {
        return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
                .apiInfo(apiInfo())
                .includePatterns(".*")
                .apiVersion("0.0.1");
        //.swaggerGroup(PROJECT_NAME);
    }

    private ApiInfo apiInfo() {
        ApiInfo apiInfo = new ApiInfo(
                PROJECT_NAME + " API",
                PROJECT_NAME + " 后台API文档",
                "http://127.0.0.1:9081/api",
                "[email protected]",
                "MTA License",
                "MTA API License URL"
        );
        return apiInfo;
    }
}

Api跳转Controller

/*
 * Copyright (c) 2015. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

 
import com.mangofactory.swagger.annotations.ApiIgnore;
import com.meituan.hotel.common.constants.LogConstants;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
/**
 * API访问Controller
 * 使用HttpClient中转请求
 * Created by liuxinyu on 15/4/24.
 */
@Controller
@ApiIgnore
@RequestMapping("/api")
public class SpringFoxController {
 
    private final static Log logger = LogFactory.getLog(LogConstants.LOG_LEVEL_INFO);
    private final static String COLON = ":";
    private final static String API_DOC = "/api-docs";
 
    @RequestMapping("/")
    public void api(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取url地址
        String reqUrl = request.getRequestURL().toString();
        logger.info("api页面请求:" + reqUrl);
        reqUrl = reqUrl.replace("api", "api") + "/index.html";
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(reqUrl);
        client.executeMethod(method);
        //api url
        String apiUrl = request.getServerName() + COLON + request.getServerPort() + API_DOC;
 
        String html = method.getResponseBodyAsString();
        //处理html页面内容,使其可以访问静态资源
        String body = html.replace("petstore.swagger.io/v2/swagger.json", apiUrl)
                .replace("css/", "/api/css/")
                .replace("lib/", "/api/lib/")
                .replace("swagger-ui.js", "/api/swagger-ui.js");
        response.getWriter().write(body);
        response.getWriter().flush();
    }
}

三、效果

访问$server:$port/api/

技术分享


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。