1.pom.xml 添加swagger2依赖
注意:springboot和swagger2的版本号
此处使用:springboot: 2.5.6
swagger2: 2.7.0
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<!--swagger-ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
2.添加Swagger2Config配置文件
title替换成您项目的名称
eg:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder().title("微信支付案例接口文档").build());
}
}
3.控制层添加Swagger2的注解
按需要填写:@Api(tags = "xx")、@ApiOperation("xx")
eg:
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(tags = "商品管理")
@RestController
@RequestMapping("/api/product")
public class ProductController {
@ApiOperation("测试接口")
@GetMapping("/test")
public String test(){
return "test";
}
}
4.运行项目:http://localhost:xx/swagger-ui.html
xx:您项目端口号
运行结果:
5.点击商品管理(tags 自己起的名)
点击测试接口
点击Try it out