springboot3使用swagger文档

1. 引入依赖

在pom.xml里面引入如下俩个依赖

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

        
            org.springdoc
            springdoc-openapi-starter-webmvc-ui
            2.0.2
            
                
                    slf4j-api
                    org.slf4j
                
            
        

2. 配置application.yml文件(其实不配置也行)

server:
  port: 8080
# 配置swagger文档的访问路径
springdoc:
  swagger-ui:
    path: /swagger-ui.html

3. 编写swagger配置类SwaggerConfig

package com.config;

import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SwaggerConfig {

    @Bean
    public OpenAPI springShopOpenAPI() {
        return new OpenAPI()
                .info(new Info().title("标题")
                        .description("我的API文档")
                        .version("v1")
                        .license(new License().name("Apache 2.0").url("http://springdoc.org")))
                .externalDocs(new ExternalDocumentation()
                        .description("外部文档")
                        .url("https://springshop.wiki.github.org/docs"));
    }

}

4. 编写一个测试用的controller类

package com.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Tag(name = "测试Controller", description = "这是描述")
public class IndexController {

    @GetMapping("/hello")
    @Operation(summary = "测试接口")
    public String index(@Parameter(name = "name", description = "名称") String name) {
        return "hello " + name;
    }

}

5. 编写启动类Application

package com;

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

@SpringBootApplication
public class Application {

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

然后启动项目,打开浏览器访问 http://localhost:8080/swagger-ui.html

springboot3使用swagger文档_第1张图片

就可以看到生成的文档了 

最后附上swagger2到open api的注解变化

springboot3使用swagger文档_第2张图片

 

 

你可能感兴趣的:(java,spring)