第1步: 准备SpringBoot项目
这一步省略了,请自行创建好SpringBoot项目。
第2步:在pom.xml文件中添加必要的依赖
<dependency>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-core</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
不解释
第3步:创建Swagger的配置类
package com.wanshi.springboot03.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.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConf {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("SpringBoot03 API Doc")
.description("This is a restful api document of SpringBoot03.")
.version("1.0")
.build();
}
}
第4步:在类和方法前添加注解
注解类似下面
@Api(value = "类说明")
@CrossOrigin
@RestController
public class TestController {
@ApiOperation(value = "方法说明", notes = "")
@PostMapping("/test1")
public Map<String,Object> test1(@RequestBody(required = false) Map<String,Object> param){
// 中间的代码省略
}
}
第5步:启动并测试
启动SpringBoot项目,访问地址: http://127.0.0.1:8080/swagger-ui/index.html
注意:这个地址是 Swagger3.0 版本的,以前版本的地址是 swagger-ui.html
访问接口文档并测试的步骤省略了。