springboot简单使用swagger

目录

  • 目前可以选择使用swageer2或swagger3
    • swagger2
      • 导入swagger2和ui依赖
      • 创建一个controller
      • 配置swagger
      • 运行项目,访问http://localhost:8080/swagger-ui.html
    • swagger3
      • 导入依赖
      • 创建controller(与上面一致)
      • 配置swagger3
      • 运行项目,访问http://localhost:8080/swagger-ui/index.html
  • 相关知识

目前可以选择使用swageer2或swagger3

swagger2

导入swagger2和ui依赖


<dependency>
    <groupId>io.springfoxgroupId>
    <artifactId>springfox-swagger2artifactId>
    <version>2.9.2version>
dependency>

<dependency>
    <groupId>io.springfoxgroupId>
    <artifactId>springfox-swagger-uiartifactId>
    <version>2.9.2version>
dependency>

创建一个controller

package com.sky.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 创建一个Hello Worldcontroller,用来测试swagger
 */
@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello(){
        return "Hello Swagger";
    }
}

配置swagger

package com.sky.config;

import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * 使用swagger需要创建一个配置类,并开启swagger配置
 * ps:swagger和 swagger2 不能通用
 *
 * 步骤:
 * 1.将swaggerConfig注册到ioc容器中
 * 2.开启swagger2功能
 * 3.运行项目,访问swagger-ui.html
 */
@Configuration // 就是@Component
@EnableSwagger2
public class SwaggerConfig {
}

运行项目,访问http://localhost:8080/swagger-ui.html

springboot简单使用swagger_第1张图片

swagger3

导入依赖


<dependency>
    <groupId>io.springfoxgroupId>
    <artifactId>springfox-boot-starterartifactId>
    <version>3.0.0version>
dependency>

创建controller(与上面一致)

配置swagger3

package com.sky.config;

import org.springframework.context.annotation.Configuration;
import springfox.documentation.oas.annotations.EnableOpenApi;

/**
 * 使用swagger需要创建一个配置类,并开启swagger配置
 *
 * 步骤:
 * 1.将swaggerConfig注册到ioc容器中
 * 2.开启swagger3功能
 * 3.运行项目,访问http://localhost:8080/swagger-ui/index.html
 */
@Configuration // 就是@Component
@EnableOpenApi // 开启swagger3功能
public class SwaggerConfig {
}

运行项目,访问http://localhost:8080/swagger-ui/index.html

springboot简单使用swagger_第2张图片

相关知识

OpenAPI 是什么?
Open API 即开放 API,也称开放平台。 所谓的开放 API(OpenAPI)是服务型网站常见的一种应用,网站的服务商将自己的网站服务封装成一系列
API(Application Programming Interface,应用编程接口)开放出去,供第三方开发者使用,这种行为就叫做开放网站的 API,所开放的 API 就被称作 OpenAPI(开放 API )。

参考资料:
https://blog.csdn.net/weixin_36836847/article/details/95206329
https://blog.csdn.net/lilinhai548/article/details/107394670

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