使用Swagger你只需要按照它的规范去定义接口及接口相关的信息,就可以做到生成接口文档,以及在线接口调试页面。
一、导入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
二、构建swagger配置类
若报空指针错误,则需在配置中添加
#Path匹配策略切换回ant_path_matcher
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
package com.xubx.springboot_01demo.configuration;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
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
@Slf4j
public class SwaggerConfiguration {
@Bean
public Docket createRestApi() {
log.info("准备生成接口文档");
ApiInfo apiInfo = new ApiInfoBuilder()
.title("个人博客接口文档")
.description("博客相关接口的文档")
.version("1.0")
.build();
//指定生成接口文档的类型
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo)
.select()
//指定生成接口需要扫描的包
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.paths(PathSelectors.any())
.build();
}
}
三、在controller中添加注解
@Controller
@Api
public class HelloController {
@ApiOperation(value = "你好")
@PostMapping("/hello")
public String hello(@ApiParam(name="name",value="对话人",required=true)String name){
return name+", hello";
}
}
上面操作都完成后,在浏览器中输入网址:localhost:8081/swagger-ui.html/,我使用的接口是默认的8081,具体以自己项目的配置为准。