前言 网络上有很多关于SpringBoot引入Swagger的教程,但是大多是针对Swagger2.x版本的教程,本着一个程序员的优良传统,我使用了Swagger3.0.0,结果踩了不少坑,在此记录一下,也方便后来者
Swagger3.x的不同 访问地址的不同 Swagger3.x:
Swagger2.x:
Swagger3.x的引入更加简洁方便 pom文件中只需写一个
1 2 3 4 5 <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0 .0 </version> </dependency>
注释添加(只需要在启动项添加一个@EnableOpenAi)
1 2 3 4 5 6 7 8 9 @EnableOpenAi @SpringBootApplication public class MyFirstSpringBootApplication { public static void main (String[] args) { SpringApplication.run(MyFirstSpringBootApplication.class, args); } }
Swagger配置类
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 33 34 package com.dreaminglri.myfirstspringboot.config;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.oas.annotations.EnableOpenApi;import springfox.documentation.service.ApiInfo;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;@EnableOpenApi @Configuration public class SwaggerConfig { @Bean public Docket createRestApi () { return new Docket (DocumentationType.OAS_30) .enable(true ) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com" )) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo () { return new ApiInfoBuilder () .title("MyFirstSpringBoot" ) .description("a project of my first spring boot learning" ) .version("1.0" ) .build(); } }
Other Problems 如果你发现启动时项目崩溃,并且显示
1 java.lang.TypeNotPresentException: Type javax.servlet.http.HttpServletRequest not present
说明你的Spring版本过高(通常为3.x),可以选择退回2.7.x版本,这样就可以正常运行Swagger
如果你执意要用Spring3.x,可以选择使用springdoc替换swagger
springdoc的内容之后会写x