Swagger接口文档:自动生成接口文档
1.添加依赖:
<!-- 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>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
2.添加配置
swagger:
title: xxx项目RESTful API
description: 开发人员太懒,没有写描述
version: 1.0
contactName: lxt
contactEmail:
contactUrl:
basePackageRest: com.qcby.xxx.rest
termsOfServiceUrl:
3.建一个properties包,建一个Swagger类
@Component
@ConfigurationProperties(prefix = "swagger")
public class SwaggerProperties {
private String title;
private String contactName;
private String contactUrl;
private String contactEmail;
private String version;
private String description;
private String basePackageRest;
private String termsOfServiceUrl;
.... get set方法
}
4.在config里创建SwaggerConfig配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Autowired
private SwaggerProperties swaggerProperties;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("REST接口")
.apiInfo(apiInfo())
.select()
// 配置自动扫描那些包下类型生成接口文档
.apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackageRest()))
.build();
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title(swaggerProperties.getTitle())
//创建人
.contact(new Contact(swaggerProperties.getContactName(), swaggerProperties.getContactUrl(),swaggerProperties.getContactEmail()))
//版本号
.version(swaggerProperties.getVersion())
//描述
.description(swaggerProperties.getDescription())
.build();
}
}
注意:
1.
如果我们不给controller层的接口加get、post请求方法,那么会出现这么一种情况:
一个方法会有多种请求方式,当接口非常多的时候就会很多,所以我们需要加上请求方法,post方法:@Postmapping
get、post方法:@RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})