Swagger之SpringMVC集成(springfox)

1、添加依賴pom.xml

<dependencies>
        <!-- log4j2 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
        </dependency>
        <!-- servlet 3.0 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version><!--$NO-MVN-MAN-VER$ -->
        </dependency>
        <!-- spring mvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <!-- spring-fox -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.5.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.5.0</version>
        </dependency>
        <!-- jackson -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.8.5</version>
        </dependency>
    </dependencies>
2、spring.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

    <!-- 配置自動掃描 -->
    <context:component-scan base-package="com.github"/>
</beans>

3、SpringMVC配置spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd 
   http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <context:component-scan base-package="com.github.swagger.web"/>
    
    <bean name="applicationSwaggerConfig" class="com.github.config.SwaggerConfig"/>
    
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
        <property name="order" value="0"/>
    </bean>
    
    <mvc:default-servlet-handler/>

    <mvc:annotation-driven >
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- Enables swgger ui-->
    <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
    <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
</beans>
4、web容器配置 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name>spring-swagger-integration</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

5.Springfox swagger配置

/**
* ClassName : SwaggerConfig.java
* Create on :2017年1月12日
* Copyrights 2017 guanfl All rights reserved.
* Email : [email protected]
*/
package com.github.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableWebMvc
@EnableSwagger2
public class SwaggerConfig {
    
    @Bean
    public Docket customDocket() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()); 
    }
    
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder().title("測試API接口文檔").description("©2017 Copyright. Powered By https://github.com/guanfl")
                .contact(new Contact("guanfl", "", "[email protected]")).license("Apache License Version 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html").version("2.0").build();
    }
}
6、接口代碼

/**
* ClassName : SwaggerController.java
* Create on :2016年12月30日
* Copyrights 2016 guanfl All rights reserved.
* Email : [email protected]
*/
package com.github.swagger.web;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(value = "restful", description = "關於Restful接口文檔註釋")
@RestController
@RequestMapping("swagger")
public class SwaggerController {

    @ApiOperation(value = "GET獲取數據",produces="application/json")
    @RequestMapping(value = "resource/{id}", method = RequestMethod.GET)
    public ResponseEntity<ModelMap> swaggerGetResource(@ApiParam(name = "id", value = "編號", required = true) @PathVariable String id) {
        ModelMap modelMap = new ModelMap();
        modelMap.put("httpCode", HttpStatus.OK.value());
        modelMap.put("msg", HttpStatus.OK.getReasonPhrase());
        modelMap.put("timestamp", System.currentTimeMillis());
        modelMap.put("apiversion", 2);
        return ResponseEntity.ok(modelMap);
    }
    
    @ApiOperation(value = "POST新增數據")
    @RequestMapping(value = "resource/{id}", method = RequestMethod.POST)
    public ResponseEntity<ModelMap> postResource(@ApiParam(name = "id", value = "編號", required = true) @PathVariable String id){
        ModelMap modelMap = new ModelMap();
        modelMap.put("status", HttpStatus.BAD_REQUEST.value());
        modelMap.put("timestamps",System.currentTimeMillis());
        modelMap.put("msg", HttpStatus.BAD_REQUEST.getReasonPhrase());
        modelMap.put("apiversion", 2);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(modelMap);
    }
    
    
    @ApiOperation(value = "DELETE刪除數據")
    @RequestMapping(value = "resource/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<ModelMap> deleteResource(@ApiParam(name = "id", value = "編號", required = true) @PathVariable String id){
        ModelMap modelMap = new ModelMap();
        modelMap.put("status", HttpStatus.OK.value());
        modelMap.put("timestamps",System.currentTimeMillis());
        modelMap.put("msg", HttpStatus.OK.getReasonPhrase());
        modelMap.put("apiversion", 2);
        return ResponseEntity.status(HttpStatus.OK).body(modelMap);
    }
    
    @ApiOperation(value = "PUT更新數據")
    @RequestMapping(value = "resource/{id}", method = RequestMethod.PUT)
    public ResponseEntity<ModelMap> updateResource(@ApiParam(name = "id", value = "編號", required = true) @PathVariable String id){
        ModelMap modelMap = new ModelMap();
        modelMap.put("status", HttpStatus.OK.value());
        modelMap.put("timestamps",System.currentTimeMillis());
        modelMap.put("msg", HttpStatus.OK.getReasonPhrase());
        modelMap.put("apiversion", 2);
        return ResponseEntity.status(HttpStatus.OK).body(modelMap);
    }
}

DONE!!!
參考代碼地址:https://github.com/guanfl/spring-swagger-integration

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章