pom.xml
<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>
config
ConditionalOnProperty表示在配置文件中添加swagger.enable=true之后, 此类才会被加载, swagger才可以被使用, 可用于测试生产环境做不同配置
@Configuration
@EnableSwagger2
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.smartdevice")) // 扫描包路径
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("接口文档")
.description("Service接口文档")
.contact(new Contact("GuanDS", "https://blog.csdn.net/guandongsheng110", "156545385@qq.com"))
.version("1.0.0")
.build();
}
}
yml
swagger:
enable: true
Controller
类上添加@Api, 方法上添加@ApiOperation
@RestController
@Api("设备日志")
public class DeviceLogController implements DeviceLogFeign {
@Autowired
private DeviceLogService deviceLogService;
@Override
@ApiOperation(value = "设备列表")
public PageInfo<DeviceLogResponse> list(DeviceLogRequest request)
return null;
}
}
DTO
对象上添加@ApiModel, 属性上添加@ApiModelProperty
@Data
@ApiModel(value = "设备列表")
public class DeviceLogRequest {
@ApiModelProperty(value = "页码 默认1")
private int pageNum = 1;
@ApiModelProperty(value = "每页条数 默认20")
private int pageSize = 20;
}
访问swagger-ui
http://127.0.0.1:8078/swagger-ui.html
请求
输入参数, 点击按钮, 测试请求
当yml中swagger.enable值为false时, 访问swagger页面异常
尤其注意的点: 生产环境应禁用Swagger