SpringBoot中配置Swagger2

发布时间 2023-04-18 23:36:16作者: 3rdtsuki

首先在pom.xml添加springfox-swagger2和springfox-swagger-ui两个依赖,并且spring-boot-starter-parent的版本不能太高,可以设置为2.1.6.RELEASE

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.9.2</version>
</dependency>

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.9.2</version>
</dependency>

在config/目录下创建一个SwaggerConfig.java。

package com.example.springdemo.config;

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

@Configuration
@EnableSwagger2
public class SwaggerConfig {
}

如果@EnableSwagger2注解无法识别的话,需要点击这个循环图标重新加载maven project即可
image

在application.properties中添加下面代码,否则运行时会报空指针错误

spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER

运行项目,访问 http://localhost:8080/swagger-ui.html 即可看到Swagger界面
image