本文部分内容是从这里获得

Swagger3.0介绍及springboot整合Swagger3.0_swagger 3.0-CSDN博客

前提

Springboot3 变化

img

查看api的地址

  • springboot3

http://localhost:8080/swagger-ui/index.html

  • springboot2

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

依赖导入

这个需要根据根据你的springboot 版本来决定版本的

  • 如果你是 springboot3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.0.2</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
  • 如果你是springboot2
1
2
3
4
5
6
7
8
9
10
11
12
13
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>

<!--swagger ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>

application.yaml

只有springboot3 需要这一步

1
2
3
4
5
6
springdoc:
swagger-ui:
path: /swagger-ui.html
logging:
level:
com.hexadecimal: debug

Config

  • springboot2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer{

@Bean
public Docket docket(Environment environment) {
Profiles profiles = Profiles.of("pro");
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(!flag)
.select()
//这里需要修改名称
.apis(RequestHandlerSelectors.basePackage("com.history.controller"))
.paths(PathSelectors.any())
.build();

}


private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//这里时你的标题
.title("阁中汗青小程序")
.description("接口说明")
.version("1.0.0")
// 作者信息
.contact(new Contact("宇神", "", ""))
.build();
}
}

  • springboot3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25


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"));
}

}

剩下这些可以自行去网上搜索, 不同版本的语法不同

Controller

这里的控制类 @Api ,tags 为类型

1
2
@Api(tags = "文章模块")
public class ArticleController{}

Entity

这类似乎不用写

Dto

模块类

1
2
@ApiModel(description = "前端传过来的创作实体类")
public class LiteraryDto {}