环境配置
SpringBoot | springfox-swagger2 | springfox-swagger-ui |
---|---|---|
2.1.5 | 2.9.2 | 2.9.2 |
pom.xml
<!-- 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>
Swagger配置
@Configuration
@EnableSwagger2
public class SwaggerConfigs {
/**
* 创建API应用
* apiInfo() 增加API相关信息
* 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
* 本例采用指定扫描的包路径来定义指定要建立API的目录。
* @return
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.swagger.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
/**
* 创建该API的基本信息(这些基本信息会展现在文档页面中)
* 访问地址:http://项目实际地址/swagger-ui.html
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("标题:API示例接口")
.description("描述:Demo示例接口")
.version("版本号:0.0.1")
.build();
}
}
Controller
/**
* 自动扫描,可不添加
* Api()规定Controller
* ApiOperation()规定接口
* ApiParam()规定参数
*/
@RestController
@RequestMapping("api")
@Api(description = "API接口示例")
public class APIController {
@GetMapping("get")
public String getDemo(
@RequestParam(required = true, value = "name") String name ){
return "Hello "+ name;
}
@ApiOperation(value = "get接口示例")
@GetMapping("getAPIDemo")
public String getAPIDemo(
@RequestParam(required = true, value = "name") @ApiParam(required = true, value = "name")String name ){
return "Hello "+ name;
}
@ApiOperation(value = "postDemo")
@PostMapping("post")
public String postDemo(
@RequestParam(required = true, value = "name") @ApiParam(required = true, value = "name")String name ){
return "Hello "+ name;
}
}
调试效果
访问地址:http://项目实际地址/swagger-ui.html
示例代码
https://github.com/sleetdream/swaggerdemo