SpringMVC项目接入Springfox

一、简介

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

二、接入

1、pom依赖

1)必要



    com.mangofactory
    swagger-springmvc
    1.0.2



    com.fasterxml.jackson.core
    jackson-databind
    2.4.2



    org.webjars.bower
    swagger-ui
    2.1.8-M1

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


    org.springframework
    spring-web
    3.2.0.RELEASE


    com.google.guava
    guava
    15.0

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 代替
 * 

*

@author 刘新宇 *

*

@date 2015年4月26日 下午1:18:48 *

@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/


你可能感兴趣的:(日记)