spring-boot集成swagger(接口管理工具)

(1)Swagger的产生

       我们的RESTful API需要面对多个开发人员或多个开发团队:IOS开发、Android开发或是Web开发等。为了减少与其他团队平时开发期间的频繁沟通成本,传统做法我们会创建一份RESTful API文档来记录所有接口细节,然而这样的做法有以下几个问题:

 

    由于接口众多,并且细节复杂(需要考虑不同的HTTP请求类型、HTTP头部信息、HTTP请求内容等),高质量地创建这份文档本身就是件非常吃力的事,下游的抱怨声不绝于耳。

    随着时间推移,不断修改接口实现的时候都必须同步修改接口文档,而文档与代码又处于两个不同的媒介,除非有严格的管理机制,不然很容易导致不一致现象。

       Swagger的产生就是为了解决以上这些问题。

(2)Swagger的介绍

       Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。

       接下来我们介绍spring boot怎么集成swagger。

(3)开始集成

pom.xml

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     <!-- jdk版本号,angel在这里使用1.8,大家修改为大家本地配置的jdk版本号即可 -->
    <java.version>1.7</java.version>
  </properties>
 
<!--
       spring boot 父节点依赖,
       引入这个之后相关的引入就不需要添加version配置,
       spring boot会自动选择最合适的版本进行添加。
     -->
    <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>1.3.3.RELEASE</version>
    </parent>
 
 
  <dependencies>
   
    <!-- spring boot web支持:mvc,aop... -->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
       </dependency>
      
         <!-- Swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>
 
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>
 
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
        </dependency>

启动App.java

package com.zjq.lvpp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

swagger配置SwaggerConfig.java(在这里我配置了两个controller分别是"/api/.*"和"/demo/.*")


两个controller,TestController.java,DemoController.java
package com.zjq.lvpp.controller;

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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestController {

	@ResponseBody
	@RequestMapping(value="/api/test/show",method=RequestMethod.GET)
	@ApiOperation(value="显示接口", notes="显示详细描述")
	public String show(@ApiParam(required=true, value="姓名") @RequestParam(name = "name") String name){
		return name;
	}
	
	@ResponseBody
	@RequestMapping(value="/api/test/test",method=RequestMethod.GET)
	@ApiOperation(value="测试接口", notes="测试接口详细描述")
	public String test(){
		return "success";
	}
}
package com.zjq.lvpp.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import io.swagger.annotations.ApiOperation;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zjq.lvpp.demo.Demo;

import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping(value="/demo")
public class DemoController {
	private Logger logger = LoggerFactory.getLogger(DemoController.class);
	
	/**
     * 可以直接使用@ResponseBody响应JSON
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getcount", method = RequestMethod.POST)
    @ApiOperation(value="测试-getCount", notes="getCount更多说明")
    public ModelMap getCount(HttpServletRequest request,
            HttpServletResponse response) {
        logger.info(">>>>>>>> begin getCount >>>>>>>>");
        ModelMap map = new ModelMap();
        map.addAttribute("count", 158);
 
        // 后台获取的国际化信息
        map.addAttribute("xstest", "测试");
        return map;
    }
    
    @ApiIgnore//使用该注解忽略这个API
    @ResponseBody
    @RequestMapping(value = "/jsonTest1", method = RequestMethod.POST)
    public ModelMap jsonTest(HttpServletRequest request,
            HttpServletResponse response) {
        ModelMap map = new ModelMap();
        map.addAttribute("hello", "你好");
        map.addAttribute("veryGood", "很好");
 
        return map;
    }
    
    @ResponseBody
    @RequestMapping(value = "/jsonTest3", method = RequestMethod.POST)
    public List<String> jsonTest3(HttpServletRequest request,
            HttpServletResponse response) {
        List<String> list = new ArrayList<String>();
        list.add("hello");
        list.add("你好");
        return list;
    }
    
    /**
     * JSON请求一个对象<br/>
     * (Ajax Post Data:{"name":"名称","content":"内容"})
     *
     * @param version
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/jsonTest2", method = RequestMethod.GET)
    public ModelMap jsonTest2(@RequestBody Demo demo, @RequestParam String name) {
        logger.info("demoName:" + demo.getName());
        logger.info("demoContent:" + demo.getContent());
        logger.info("name:" + name);
        ModelMap map = new ModelMap();
        map.addAttribute("result", "ok");
        return map;
    }
    
    /**
     * 直接读取URL参数值<br/>
     * /demo/jsonTest6.do?name=Hello&content=World
     *
     * @param demoName
     * @param content
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/jsonTest6", method = RequestMethod.POST)
    public ModelMap jsonTest6(@RequestParam("name") String demoName, @RequestParam String content) {
        logger.info("demoName:" + demoName);
        ModelMap map = new ModelMap();
        map.addAttribute("name",demoName + "AAA");
        map.addAttribute("content",content + "BBB");
        map.addAttribute("date",new java.util.Date());
        return map;
    }
    
    /**
     * JSON请求一个对象,将RequestBody自动转换为JSONObject对象<br/>
     * (Ajax Post Data:{"name":"名称","content":"内容"})
     *
     * 使用JSONObject请添加依赖
     *  <dependency>
     *      <groupId>net.sf.json-lib</groupId>
     *      <artifactId>json-lib</artifactId>
     *      <version>2.4</version>
     *      <!--指定jdk版本 -->
     *      <classifier>jdk15</classifier>
     *  </dependency>
     *
     * @param version
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/jsonTest5", method = RequestMethod.POST)
    public ModelMap jsonTest5(@RequestBody JSONObject jsonObject) {
        String name = jsonObject.getString("name");
        logger.info("demoName:" + name);
        ModelMap map = new ModelMap();
        map.addAttribute("demoName",name);
        return map;
    }
 
    /**
     * 输入和输出为JSON格式的数据的方式 HttpEntity<?> ResponseEntity<?>
     *
     * @param u
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/jsonTest4", method = RequestMethod.POST)
    public ResponseEntity<String> jsonTest4(HttpEntity<Demo> demo,
            HttpServletRequest request, HttpSession session) {
        //获取Headers方法
        HttpHeaders headers = demo.getHeaders();
 
        // 获取内容
        String demoContent = demo.getBody().getContent();
 
        // 这里直接new一个对象(HttpHeaders headers = new HttpHeaders();)
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("MyHeaderName", "SHANHY");
 
        ResponseEntity<String> responseResult = new ResponseEntity<String>(
                demoContent, responseHeaders, HttpStatus.OK);
        return responseResult;
    }
}

实体Demo.java
package com.zjq.lvpp.demo;

public class Demo {
	private Long id;
	private String name;
	private String content;
	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 getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	
}

测试:http://localhost:8080/swagger-ui.html 


相关内容推荐