搭建简单的springboot整合swagger的Demo

Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。本文简单介绍了在项目中集成swagger的方法和一些常见问题。如果想深入分析项目源码,了解更多内容,见参考资料。

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

一、使用介绍
什么是 Swagger?
Swagger™的目标是为REST APIs 定义一个标准的,与语言无关的接口,使人和计算机在看不到源码或者看不到文档或者不能通过网络流量检测的情况下能发现和理解各种服务的功能。当服务通过Swagger定义,消费者就能与远程的服务互动通过少量的实现逻辑。类似于低级编程接口,Swagger去掉了调用服务时的很多猜测。
浏览 Swagger-Spec 去了解更多关于Swagger 项目的信息,包括附加的支持其他语言的库。

swagger的初级使用

  1. 创建项目springbooot-web
    项目结构
    搭建简单的springboot整合swagger的Demo_第1张图片
  2. 添加swagger依赖包
 
        
            io.springfox
            springfox-swagger2
            2.2.2
        
        
            io.springfox
            springfox-swagger-ui
            2.2.2
        
  1. 添加控制api(创建testSwagger2Controller.class)
package com.xpf.controller;

import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 */
@RestController
public class testSwagger2Controller{

        @ApiOperation(value = "测试Swagger能否使用")
        @GetMapping(value = "/index")
        public String test() {

            return "index";
        }

}

  1. 编写Swagger Bean,已经api的定义(我是在启动类写的)
package com.xpf;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
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;

@SpringBootApplication
@Configuration
@EnableSwagger2
public class SpringSwaggerApplication {

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


    @Bean
    public Docket createApi(){
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
                .apis(RequestHandlerSelectors.basePackage("com.xpf.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("API文档")
                .description("API使用即参数定义")
                .termsOfServiceUrl("http://blog.csdn.net/qq_31001665")
                .contact("ZZP")
                .version("0.1")
                .build();
    }
}

  1. 启动访问
    搭建简单的springboot整合swagger的Demo_第2张图片

你可能感兴趣的:(swagger,springboot)