Swagger2在SpringBoot下的使用

说明

随着互联网技术的发展,现在的网站架构基本都由原来的后端渲染,变成了:前端渲染、先后端分离的形态,而且前端技术和后端技术在各自的道路上越走越远。 

为了减少与其他团队平时开发期间的频繁沟通成本,传统做法我们会创建一份RESTful API文档来记录所有接口细节,然而这样的做法有以下几个问题:

  • 由于接口众多,并且细节复杂(需要考虑不同的HTTP请求类型、HTTP头部信息、HTTP请求内容等),高质量地创建这份文档本身就是件非常吃力的事,下游的抱怨声不绝于耳。
  • 随着时间推移,不断修改接口实现的时候都必须同步修改接口文档,而文档与代码又处于两个不同的媒介,除非有严格的管理机制,不然很容易导致不一致现象。

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

 作用:

  1.     接口的文档在线自动生成。
  2.     功能测试。

快速开始

准备:springboot 2.1,sawgger 2.8.0,thymeleaf

项目地址:https://github.com/Yunlingfly/springboot-swagger2

项目结构

Swagger2在SpringBoot下的使用_第1张图片

更新pom.xml



	4.0.0

	cn.yunlingfly
	springboot-swagger
	0.0.1-SNAPSHOT
	jar

	springboot-swagger
	Demo project for Spring Boot

	
		org.springframework.boot
		spring-boot-starter-parent
		2.1.0.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-thymeleaf
		

		
			io.springfox
			springfox-swagger2
			2.8.0
		
		
			io.springfox
			springfox-swagger-ui
			2.8.0
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	

更新application.yml

server:
  port: 8081

在Application启动类同级目录新建Swagger2

package cn.yunlingfly.springbootswagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
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
@EnableSwagger2
// swagger2的配置文件,在项目的启动类的同级文件建立
public class Swagger2 extends WebMvcConfigurationSupport {
    //swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //为当前包路径
                .apis(RequestHandlerSelectors.basePackage("cn.yunlingfly.springbootswagger.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title("Spring Boot 测试使用 Swagger2 构建RESTful API")
                //创建人
                .contact(new Contact("Yunlingfly", "https://www.yunlingfly.cn", "[email protected]"))
                //版本号
                .version("1.0")
                //描述
                .description("API 描述")
                .build();
    }

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

    // 解决跨域问题
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH")
                .allowCredentials(true).maxAge(3600);
    }
}

编写bean:

package cn.yunlingfly.springbootswagger.bean;

public class TestBean {
    private String id;
    private String password;

    public String getId() {
        return id;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

编写Controller(HomeController 注解用的比较详细):

package cn.yunlingfly.springbootswagger.controller;

import cn.yunlingfly.springbootswagger.bean.TestBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
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.RestController;

@RestController
@Api("usersController相关的api")
public class TestController {
    @ApiOperation(value = "login", notes = "登录")
    @ApiImplicitParam(name = "id", value = "学生ID", paramType = "path", required = true, dataType = "Integer")
    // 用户登录
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(Integer id) {
        return "success"+id;
    }

    @ApiOperation(value = "add", notes = "添加")
    // 用户登录
    @RequestMapping(value = "/add", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String add(@RequestBody TestBean bean) {
        return "success"+bean.getId();
    }
}
package cn.yunlingfly.springbootswagger.controller;

import io.swagger.annotations.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@Api(value = "后台首页控制器")
@Controller
public class HomeController {

    @ApiOperation(value = "后台框架页面", notes = "后台框架,包含头部信息,左侧导航,脚部信息")
    @RequestMapping(value = "/index", method = {RequestMethod.GET, RequestMethod.POST})
//该注解可以单个用
//@ApiImplicitParam(name = "id", value = "其实这是演示api",defaultValue = "0", required = true, dataType = "Long", paramType = "path")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "其实这是演示api", defaultValue = "0", required = true, dataType = "Long", paramType = "path"),})
//该注解可以单个用
//@ApiResponse(code = 400, response=String.class, message = "Invalid user supplied")
    @ApiResponses({@ApiResponse(code = 400, response = String.class, message = "Invalid request type"), @ApiResponse(code = 500, message = "server is error")})

    public String home(
            @ApiParam(required = true, name = "model", value = "本次用来封装左侧导航菜单") Model model
            , HttpSession session) throws Exception {
        return "index";
    }
}

resources/templates目录下新建index.html


hello world

结果

访问:http://localhost:8081/swagger-ui.html

Swagger2在SpringBoot下的使用_第2张图片

点击try it out可以在线测试API

Swagger2在SpringBoot下的使用_第3张图片

你可能感兴趣的:(Spring,Boot,swagger2,springboot)