ASP源码.NET源码PHP源码JSP源码JAVA源码DELPHI源码PB源码VC源码VB源码Android源码
当前位置:首页 >> 网络编程 >> Java教程 >> SpringMVC项目接入Springfox

SpringMVC项目接入Springfox

来源:网络整理     时间:2015-05-20     关键词:

本篇文章主要介绍了"SpringMVC项目接入Springfox",主要涉及到方面的内容,对于Java教程感兴趣的同学可以参考一下: 一、简介Springfox的前身是swagger-springmvc,是一个开源的API doc框架,可以将我们的Controller的方法以文档的形式展现。二...

一、简介

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",
                "your@company.com",
                "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/

以上就介绍了SpringMVC项目接入Springfox,包括了方面的内容,希望对Java教程有兴趣的朋友有所帮助。

本文网址链接:http://www.codes51.com/article/detail_136374.html

相关图片

相关文章