SpringMVC、SpringFox和Swagger整合項目實例


目標

在做項目的時候,有時候需要提供其它平台(如業務平台)相關的HTTP接口,業務平台則通過開放的HTTP接口獲取相關的內容,並完成自身業務~

提供對外開放HTTP API接口,比較常用的是采用Spring MVC來完成。

本文的目標是先搭建一個簡單的Spring MVC應用,然后為Spring MVC整合SpringFox-Swagger以及SpringFox-Swagger-UI,最終,達到Spring MVC對外開放接口API文檔化。

如下圖所示:

搭建SpringMVC工程

新建Maven工程

Eclipse中,File --> New --> Maven Project, 

點擊“Next”按鈕, 然后選擇 “maven-archetype-webapp”,

繼續點擊“Next”按鈕,然后指定

點擊“Finish” 按鈕結束~ 就這樣,一個簡單的Web工程就建好了~

但是,

默認是使用J2SE-1.5, 配置一下Build Path,使用本地機器上安裝的JDK

(本文中使用的是JDK 1.7),工程默認字體是GBK,將其改成UTF-8

完成后,Maven工程的結構如下圖所示:

引入Spring依賴包

在本示例中,因為簡單,所以只要引入如下幾個jar包就好了~

<dependencies>
        <!--引入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>

 

完整的pom.xml文件內容如下:

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.xxx.tutorial</groupId>
    <artifactId>springfox-swagger-demo</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>springfox-swagger-demo Maven Webapp</name>
    <url>http://maven.apache.org</url>

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

    <dependencies>
        <!--引入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>springfox-swagger-demo</finalName>
    </build>
</project>

 

編寫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 />

    <!-- 設置使用注解的類所在的jar包 -->
    <context:component-scan base-package="com.htjf.controller" />  <!--這個是我的項目包結構-->
    
</beans>

 

配置applicationContext.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:p="http://www.springframework.org/schema/p"
    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.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd">
        
        <!-- 啟用注解掃描,並定義組件查找規則 ,除了@controller,掃描所有的Bean -->
        <context:component-scan base-package="com.htjf"/>
        
         <!-- 啟動SpringMVC的注解功能,完成請求和注解POJO的映射 -->
        <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

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

 

 

配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
         version="3.1">
  <display-name>Archetype Created Web Application</display-name>

    <!-- 利用Spring提供的ContextLoaderListener監聽器去監聽ServletContext對象的創建,並初始化WebApplicationContext對象 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- Context Configuration locations for Spring XML files(默認查找/WEB-INF/applicationContext.xml) -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
 
<!-- 配置Spring MVC的前端控制器:DispatchcerServlet -->
  <servlet>
    <servlet-name>springmvc</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>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!--字符編碼過濾器-->
  <filter>
    <filter-name>encoding</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>encoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

 

編寫Controller並測試

配置好spring-mvc.xml、applicationContext.xml以及web.xml文件之后,咱們繼續往下走~

因為,本文Spring MVC示例的作用主要用來暴露對外HTTP API接口,先寫一個簡單的ProductController,其包含一個按照id查詢的方法。

Product.java和ProductController.java的內容如下:

Product.java

package com.xxx.tutorial.model;

import java.io.Serializable;

/**
 * 
 * @author wangmengjun
 *
 */
public class Product implements Serializable {

    private static final long serialVersionUID = 1L;

    /**ID*/
    private Long id;

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

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

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

    /**
     * @return the id
     */
    public Long getId() {
        return id;
    }

    /**
     * @param id
     *            the id to set
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the productClass
     */
    public String getProductClass() {
        return productClass;
    }

    /**
     * @param productClass
     *            the productClass to set
     */
    public void setProductClass(String productClass) {
        this.productClass = productClass;
    }

    /**
     * @return the productId
     */
    public String getProductId() {
        return productId;
    }

    /**
     * @param productId
     *            the productId to set
     */
    public void setProductId(String productId) {
        this.productId = productId;
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + ", productClass=" + productClass + ", productId=" + productId
                + "]";
    }

}

 

ProductController.java

package com.xxx.tutorial.controller;

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.xxx.tutorial.model.Product;

@RestController
@RequestMapping(value = { "/api/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("seven_filters");
        product.setProductId("T12345");
        return ResponseEntity.ok(product);
    }
}

 

注:

鑒於是一個demo示例,所以沒有寫ProductService以及相關DAO, 直接在方法中返回固定的Product信息~

驗證Spring MVC是否ok

完成Controller的代碼,運行Spring MVC項目,然后,看一下Spring MVC是否運行ok,訪問URL地址

http://localhost:8888/springfox-swagger-demo/api/product/1

  • 出現錯誤

詳細的錯誤信息如下:

五月 23, 2017 3:00:55 下午 org.apache.catalina.core.StandardWrapperValve invoke
嚴重: Servlet.service() for servlet [spring-mvc] in context with path [/springfox-swagger-demo] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: No converter found for return value of type: class com.xxx.tutorial.model.Product] with root cause java.lang.IllegalArgumentException: No converter found for return value of type: class com.xxx.tutorial.model.Product at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:187) at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:203) at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) at javax.servlet.http.HttpServlet.service(HttpServlet.java:624) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source) 

解決方法,添加jackson-databind依賴包即可~

<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.6.6</version>
        </dependency>

 

 

重新啟動,運行一下,成功返回信息~

為了看的更加清楚,可以使用postman來完成~, 如~

至此,一個簡單的基於SpringMVC的Web項目已經創建,並能對外提供API接口~ 

接下來,我們要整合SpringFox和SwaggerUI到該SpringMVC項目中去,使其對外接口文檔化

整合SpringFox-Swagger

SpringFox【SpringFox鏈接】已經可以代替Swagger-SpringMVC, 目前SpringFox同時支持Swagger 1.2 和 2.0.

在SpringMVC項目中整合SpringFox-Swagger只要如下幾步即可~

  • 添加SpringFox-Swagger依賴
  • 添加SwaggerConfig

添加依賴

<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>

 

添加SwaggerConfig

package com.htjf.config;

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 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
@ComponentScan(basePackages= {"com.htjf.controller"})
@EnableWebMvc
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }
    
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("對外開放接口API 文檔")               //大標題 title
                .description("HTTP對外開放接口")             //小標題
                .version("1.0.0")                           //版本
                .termsOfServiceUrl("http://xxx.xxx.com")    //終端服務程序
                .license("LICENSE")                         //鏈接顯示文字
                .licenseUrl("http://xxx.xxx.com")           //網站鏈接
                .build();
    }
}

 

整合SpringFox-Swagger-UI

在SpringMVC項目中整合SpringFox-Swagger-UI也只要如下兩個步驟即可~

  • 添加SpringFox-Swagger-UI依賴
  • 添加配置

添加依賴

<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>

 

 

添加配置

在添加配置之前,一起來看一下swagger-ui中使用的靜態資源文件(如 swagger-ui.html )放在那里~

spingfox-swagger-ui-2.7.0.jar中的/META-INF/resources/下~ 如下圖所示:

 

為了訪問swagger-ui.html,我們配置對這些靜態資源的訪問~ 如:

package com.xxx.tutorial.config;

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/");
    }

}

 

該配置代碼的效果和如下代碼等價~

<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
    <mvc:resources mapping="/webjars/**"
        location="classpath:/META-INF/resources/webjars/" />

 

 

在本文中,可以將其配置在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 />

    <!-- 設置使用注解的類所在的jar包 -->
    <context:component-scan base-package="com.htjf.controller" />
    
    <mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/>
    <mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>
</beans>

 

 

 

API接口說明代碼添加並測試

經過上述幾個步驟之后,之前寫的ProductController的接口,就可以實現文檔化了,如本文通過如下的訪問地址訪問:

http://localhost:8888/springfox-swagger-demo/swagger-ui.html

這個接口API雛形出來了,但是還缺少點東西,比如:接口方法的描述等都沒有~

修改一下,ProductController.java內容,如:

package com.xxx.tutorial.controller;

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.xxx.tutorial.model.Product;

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

@RestController
@RequestMapping(value = { "/api/product/" })
@Api(value = "/product", tags = "Product接口")
public class ProductController {

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @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("seven_filters");
        product.setProductId("T12345");
        return ResponseEntity.ok(product);
    }
}

 

重新訪問,接口已經出現多個我們指定的描述信息~

 

在參數id欄中輸入1,然后點擊“try it out”按鈕~ 可以查看接口調用結果~

至此一個簡單的示例就完成了~

稍微增加幾個接口

修改ProductController

package com.xxx.tutorial.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.xxx.tutorial.model.Product;

    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import io.swagger.annotations.ApiResponse;
    import io.swagger.annotations.ApiResponses;

    @RestController
    @RequestMapping(value = { "/api/product/" })
    @Api(value = "/product", tags = "Product接口")
    public class ProductController {

        @RequestMapping(value = "/{id}", method = RequestMethod.GET)
        @ApiResponses(value= {
                @ApiResponse(code = 400,message="參數錯誤"),
                @ApiResponse(code = 401,message="要求用戶的身份認證"),
                @ApiResponse(code = 403,message="拒絕執行此請求"),
                @ApiResponse(code = 404,message="系統資源未發現"),
                @ApiResponse(code = 500,message="系統錯誤"),
                @ApiResponse(code = 200,message="成功,其它為錯誤,返回格式:{code:0,data[{}]},data中的屬性參照下方Model",response=Product.class)})
        @ApiOperation(value = "根據id獲取產品信息", notes = "根據id獲取產品信息", httpMethod = "GET")
        public ResponseEntity<Product> get(@PathVariable Long id) {
            Product product = new Product();
            product.setName("七級濾芯凈水器");
            product.setId(1L);
            product.setProductClass("seven_filters");
            product.setProductId("T12345");
            return ResponseEntity.ok(product);
        }

        @RequestMapping(method = RequestMethod.POST)
        @ApiOperation(value = "添加一個新的產品")
        @ApiResponses(value = { 
                @ApiResponse(code = 201,message="已創建。成功請求並創建了新的資源"),
                @ApiResponse(code = 401,message="要求用戶的身份認證"),
                @ApiResponse(code = 403,message="拒絕執行此請求"),
                @ApiResponse(code = 404,message="系統資源未發現"),
                @ApiResponse(code = 405, message = "參數錯誤"), 
                @ApiResponse(code = 200,message="成功,其它為錯誤,返回格式:{code:0,data[{}]},data中的屬性參照下方Model",response=String.class)})
        public ResponseEntity<String> add(Product product) {
            return ResponseEntity.ok("SUCCESS");
        }

        @RequestMapping(method = RequestMethod.PUT)
        @ApiOperation(value = "更新一個產品")
        @ApiResponses(value = { 
                @ApiResponse(code = 200,message="成功,其它為錯誤,返回格式:{code:0,data[{}]},data中的屬性參照下方Model",response=String.class),
                @ApiResponse(code = 201,message="已創建。成功請求並創建了新的資源"),
                @ApiResponse(code = 400, message = "參數錯誤"),
                @ApiResponse(code = 401,message="要求用戶的身份認證"),
                @ApiResponse(code = 403,message="拒絕執行此請求"),
                @ApiResponse(code = 404,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));
        }
    }

    @RequestMapping(method=RequestMethod.DELETE)
    @ApiOperation(value="刪除某個產品信息",notes="刪除某個產品信息")
/*    @ApiImplicitParams(@ApiImplicitParam(name="carOwnerName",value="產品id",dataType="Long"))*/
    @ApiResponses(value= {
            @ApiResponse(code = 204,message="無內容。服務器成功處理,但未返回內容!"),
            @ApiResponse(code = 400,message="參數錯誤"),
            @ApiResponse(code = 401,message="要求用戶的身份認證"),
            @ApiResponse(code = 403,message="拒絕執行此請求"),
            @ApiResponse(code = 500,message="系統錯誤"),
            @ApiResponse(code = 200,message="成功,其它為錯誤,返回格式:{code:0,data[{}]},data中的屬性參照下方Model",response=String.class)})
    public ResponseEntity<String> delete(@PathVariable Long id){
        if(carOwnerName==null) {
            return new ResponseEntity<String>(HttpStatus.NO_CONTENT);
        }else {
            return ResponseEntity.ok("SUCCESS");
        }
}

 

 

swagger-ui展示

由上圖可以看出,不同的method(GET / PUT / POST等)都會以不同的顏色展示出來~

Swagger-ui的添加,可以幫助他人查看接口信息,並在頁面上進行輸入參數來調用接口~

Maven工程的目錄如下:

本文只是一個簡單的整合示例,大家只要操作一下就能出來結果。

接下來講解Swagger 常用注解使用

--@Api()用於類;

表示這個類是一個swagger的資源。它有兩個屬性,分別是:

String value();---也是說明,可以使用tags替代 

String[] tags();---是一個數組,表示說明,tags如果有多個值,會生成多個list;

例如:

@Api(value="用戶controller",tags={"用戶操作接口"})
@RestController
public class UserController {

}

 

 

ui效果圖:

--@ApiOperation()用於方法;

表示一個http請求的操作 ,它有4個常用屬性:

String value();--用於方法描述;

String notes();--用於提示內容 

String[] tags();--可以重新分組(視情況而用)

String httpMethod(); --請求方法類型,例如:httpMethod=“GET”;

--@ApiParam() 用於方法,參數,字段說明;表示對參數的添加元數據(說明或是否必填等) ,它有幾個常用參數:

String name();--參數名

String value();--參數說明 

boolean required();--是否必填

boolean allowEmptyValue();--是否允許有空值

例如:

@Api(value="用戶controller",tags={"用戶操作接口"})
@RestController
public class UserController {
     @ApiOperation(value="獲取用戶信息",tags={"獲取用戶信息copy"},notes="注意問題點")
     @GetMapping("/getUserInfo")
     public User getUserInfo(@ApiParam(name="id",value="用戶id",required=true) Long id,@ApiParam(name="username",value="用戶名") String username) {
     // userService可忽略,是業務邏輯
      User user = userService.getUserInfo();
      return user;
  }
}

 

 

ui效果圖:

--@ApiModel()用於類 ;表示對類進行說明,用於參數用實體類接收 
value–表示對象名 
description–描述 
都可省略 
--@ApiModelProperty()用於方法,字段; 表示對model屬性的說明或者數據操作更改 
value–字段說明 
name–重寫屬性名字 
dataType–重寫屬性類型 
required–是否必填 
example–舉例說明 
hidden–隱藏

例如:

@ApiModel(value="user對象",description="用戶對象user")
public class User implements Serializable{
    private static final long serialVersionUID = 1L;
     @ApiModelProperty(value="用戶名",name="username",example="xingguo")
     private String username;
     @ApiModelProperty(value="狀態",name="state",required=true)
      private Integer state;
      private String password;
      private String nickName;
      private Integer isDeleted;
 
      @ApiModelProperty(value="id數組",hidden=true)
      private String[] ids;
      private List<String> idList;
     //省略get/set
}

 

@ApiOperation("更改用戶信息")
  @PostMapping("/updateUserInfo")
  public int updateUserInfo(@RequestBody @ApiParam(name="用戶對象",value="傳入json格式",required=true) User user){  
    
     //注意,一定要添加@RequestBody注解

     int num = userService.updateUserInfo(user);
     return num;
  }
 
        
 

ui效果圖:

--@ApiIgnore()用於類或者方法上,可以不被swagger顯示在頁面上 
比較簡單, 這里不做舉例

--@ApiImplicitParam() 用於方法 
表示單獨的請求參數 
@ApiImplicitParams() 用於方法,包含多個 @ApiImplicitParam 
name–參數ming 
value–參數說明 
dataType–數據類型 
paramType–參數類型 
example–舉例說明

*****在controller層使用@RequestParam的時候,發現這個參數是必須要輸入值的,但是我們有時候必須查詢的時候允許參數為空,使用這個注解就不行了。但是使用@ApiImplicitParam這個注解可以解決這個問題。

例如:

@ApiOperation("查詢測試")
  @GetMapping("select")
  //@ApiImplicitParam(name="name",value="用戶名",dataType="String", paramType = "query")
  @ApiImplicitParams({
  @ApiImplicitParam(name="name",value="用戶名",dataType="string", paramType = "query",example="xingguo"),
  @ApiImplicitParam(name="id",value="用戶id",dataType="long", paramType = "query")})
  public void select(){

  }
 

ui效果圖:

更加詳細的文檔,有興趣的小伙伴可以訪問swagger-ui的官網查看~


免責聲明!

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



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