Maven + SpringMVC項目集成Swagger


Swagger 是一個規范和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。總體目標是使客戶端和文件系統作為服務器以同樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,允許API來始終保持同步。

作用:

  •  接口的文檔在線自動生成。
  •  功能測試。

下面通過實現一個web項目來演示Swagger的使用。

1. 新建SpringMVC項目

1.1 新建項目

新建基於maven的web項目,導入spring相關依賴如下

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zang.xz</groupId>
    <artifactId>mySwagger</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>mySwagger Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.framework.version>4.3.6.RELEASE</spring.framework.version>
    </properties>

    <dependencies>
        <!-- ********************jackson******************************* -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.9</version>
        </dependency>
        <!-- ********************Spring依賴********************* -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>mySwagger</finalName>
    </build>
</project>

1.2 配置web.xml和spring-mvc.xml

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
  <display-name>Archetype Created Web Application</display-name>
    <!-- Spring MVC 核心控制器 DispatcherServlet 配置-->
    <servlet>
        <servlet-name>spring-mvc</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>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>  

    <!--   配置編碼格式過濾器 -->    
    <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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>  
</web-app>

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" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <!-- 默認的注解映射的支持 ,它會自動注冊DefaultAnnotationHandlerMapping 與AnnotationMethodHandlerAdapter -->
    <mvc:annotation-driven />

    <!-- enable autowire 向容器自動注冊 -->
    <context:annotation-config />

    <!-- 設置使用注解的類所在的jar包 -->
    <context:component-scan base-package="com.zang.xz" />   
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

</beans>

1.3 新建entity和controller測試

為求簡便,這里不集成dao層,數據直接從controller中封裝返回。

Product.java

package com.zang.xz.entity;

public class Product {

    private static final long serialVersionUID = 1L;

    /** ID */
    private Long id;

    /** 產品名稱 */
    private String name;

    /** 產品型號 */
    private String productClass;

    /** 產品ID */
    private String productId;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getProductClass() {
        return productClass;
    }

    public void setProductClass(String productClass) {
        this.productClass = productClass;
    }

    public String getProductId() {
        return productId;
    }

    public void setProductId(String productId) {
        this.productId = productId;
    }

    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + ", productClass="
                + productClass + ", productId=" + productId + "]";
    }

}

ProductController.java

package com.zang.xz.controller;

import java.util.Arrays;
import java.util.List;import org.springframework.http.ResponseEntity;
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 com.zang.xz.entity.Product;

@RestController
@RequestMapping(value = {"/product/"})public class ProductController {

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)public ResponseEntity<Product> get(@PathVariable Long id) {
        Product product = new Product();
        product.setName("空氣凈化器");
        product.setId(1L);
        product.setProductClass("filters");
        product.setProductId("T12345");
        return ResponseEntity.ok(product);
    }
}

測試

至此,創建了一個簡單的基於SpringMVC的Web項目,並能對外提供REST風格的API接口。接下來,我們要整合SpringFox和SwaggerUI到該SpringMVC項目中去,使其對外接口文檔化。

2. 集成Swagger

2.1 添加swagger相關jar包

<!-- swagger2核心依賴 -->
  <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.7.0</version>
  </dependency>

<!-- swagger-ui為項目提供api展示及測試的界面 -->
  <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.7.0</version>
  </dependency>

此處swagger 的核心依賴使用springfox-swagger2,SpringFox已經可以代替swagger-springmvc, 目前SpringFox同時支持Swagger 1.2 和 2.0。

 2.2 添加SwaggerConfig

package com.zang.xz.controller;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())  //顯示所有類
                //.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))  //只顯示添加@Api注解的類
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("開放接口API")  //粗標題
                .description("HTTP對外開放接口")   //描述
                .version("1.0.0")   //api version
                .termsOfServiceUrl("http://xxx.xxx.com")
                .license("LICENSE")   //鏈接名稱
                .licenseUrl("http://xxx.xxx.com")   //鏈接地址
                .build();
    }

}

2.3 靜態資源訪問配置

上面引入的springfox-swagger-ui依賴為我們提供了靜態資源訪問的支持,通過訪問他為我們提供的頁面,可以直觀的看出項目所開放的接口API。

 

要想訪問該頁面,還需要增加訪問配置,方法有兩種:

2.3.1 在spring-mvc.xml中增加配置

 <!-- swagger靜態資源訪問配置 -->
 <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
 <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />

2.3.2 或者增加配置類WebAppConfig

package com.zang.xz.controller;

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

@Configuration
@EnableWebMvc
public class WebAppConfig extends WebMvcConfigurerAdapter  {

    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}

3. 測試API接口

3.1 訪問“項目地址/swagger-ui.html#/” 查看api

訪問 http://localhost:8090/mySwagger/swagger-ui.html#/ 出現如下界面,說明我們的swagger集成項目成功。

在參數中輸入信息,可實現對接口的調用

但是單調的頁面沒有實現swagger作為API文檔工具的作用,這需要我們通過注解在接口方法中配置。

3.2 通過注解生成API文檔

常用注解如下:

常用注解: 

  • @Api()用於類; 表示標識這個類是swagger的資源 
  • @ApiOperation()用於方法; 表示一個http請求的操作 
  • @ApiParam()用於方法,參數,字段說明; 表示對參數的添加元數據(說明或是否必填等) 
  • @ApiModel()用於類 表示對類進行說明,用於參數用實體類接收 
  • @ApiModelProperty()用於方法,字段 ;表示對model屬性的說明或者數據操作更改 
  • @ApiIgnore()用於類,方法,方法參數 ;表示這個方法或者類被忽略 
  • @ApiImplicitParam() 用於方法 ;表示單獨的請求參數 
  • @ApiImplicitParams() 用於方法,包含多個 @ApiImplicitParam
@RestController
@RequestMapping(value = { "/product/" })
// 類上加@Api注解
@Api(value = "/ProductController", tags = "接口開放示例")
public class ProductController {


    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    // 方法上加ApiOpreation注解
    @ApiOperation(value = "根據id獲取產品信息", notes = "根據id獲取產品信息", httpMethod = "GET", response = Product.class)
    public ResponseEntity<Product> get(@PathVariable Long id) {
        Product product = new Product();
        product.setName("空氣凈化器");
        product.setId(1L);
        product.setProductClass("filters");
        product.setProductId("T12345");
        return ResponseEntity.ok(product);
    }
}

添加注解之后,訪問swagger界面如下

3.3 其他方法測試

多增加幾個測試方法

@RequestMapping(method = RequestMethod.POST)
    @ApiOperation(value = "添加一個新的產品")
    @ApiResponses(value = { @ApiResponse(code = 405, message = "參數錯誤") })
    public ResponseEntity<String> add(Product product) {
        return ResponseEntity.ok("SUCCESS");
    }

    @RequestMapping(method = RequestMethod.PUT)
    @ApiOperation(value = "更新一個產品")
    @ApiResponses(value = { @ApiResponse(code = 400, message = "參數錯誤") })
    public ResponseEntity<String> update(Product product) {
        return ResponseEntity.ok("SUCCESS");
    }

    @RequestMapping(method = RequestMethod.GET)
    @ApiOperation(value = "獲取所有產品信息", notes = "獲取所有產品信息", httpMethod = "GET", response = Product.class, responseContainer = "List")
    public ResponseEntity<List<Product>> getAllProducts() {
        Product product = new Product();
        product.setName("七級濾芯凈水器");
        product.setId(1L);
        product.setProductClass("seven_filters");
        product.setProductId("T12345");
        return ResponseEntity.ok(Arrays.asList(product, product));
    }

swagger界面為不同方法提供不同顏色顯示,可在其中對各個接口進行測試

 

項目結構如下:

 

 

參考:https://blog.csdn.net/u014231523/article/details/76522486

https://blog.csdn.net/eleanoryss/article/details/80609677


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM