言简意赅,直接进正题。
首先就是添加依赖:在pom.xml文件中添加依赖
<!--Swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
添加完成之后记得刷新maven,注意高版本的springboot可能兼容不了低版本的swagger,所以如果仅仅添加完swagger的依赖,运行程序发现报错,大概率是swagger版本号的问题,适当升高或降低版本即可。
其次,在application.yml文件中添加swagger的启动配置,其实很多配置都是默认项,所以不必再添加,只添加开启配置即可。
#swagger
swagger:
enable: true
最后,我们需要新建一个配置类,名字就叫swaggerConfig即可,代码如下:
package com.ycg.vue.config;
/**
* @Description swagger配置类
* @Author JK
* @Date 2024/1/2
*/
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.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
// 指定扫描的包(切换成自己项目中的包)
.apis(RequestHandlerSelectors.basePackage("com.ycg.vue.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo())
// 配置访问路径, 默认是/swagger-ui.html,可以自定义,但是需要和配置文件中的路径一致
//此处将默认的/swagger-ui.html改为/doc.html
.pathMapping("/");
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 页面标题
.title(" API ")
// 描述
.description("vue")
// 版本号
.version("0.0.1-SNAPSHOT")
.build();
}
}
运行springboot程序,然后在浏览器网址栏输入:http://localhost:8090/doc.html
至此全部完成。