api文档是一是方便前后端交互,二是为了之后的维护;但绝大多数后端不愿意去写这类文档,方法上都加注释了,还要再写一个文档。swagger就是一种自动生成api管理页面的插件。
1.导入swagger依赖包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
2.进行swagger配置,@EnableSwagger2是用来启用swagger的;很多人说是加载启动类上,两者都是可以的
@Configuration
@EnableSwagger2
public class SwaggerConfig {
public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.lawliet.juggle.api";
public static final String VERSION = "1.0.0";
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))//api接口包扫描路径
.paths(PathSelectors.any())//可以根据url路径设置哪些请求加入文档,忽略哪些请求
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger2 接口文档示例")//设置文档的标题
.description("更多内容请关注")//设置文档的描述->1.Overview
.version(VERSION)//设置文档的版本信息-> 1.1 Version information
.contact("www.baidu.com")//设置文档的联系方式->1.2 Contact information
//.termsOfServiceUrl("www.baidu.com")//设置文档的License信息->1.3 License information
.build();
}
}
3.到这一步基本都好了,在后端原来controller层中写的接口中替换原来的注解即可
@ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer",
paramType = "path")
@RequestMapping(value = "get/{id}", method = RequestMethod.POST)
public String get(HttpServletRequest request, HttpServletResponse response){
}
4.启动项目,访问http://{ip}:{port}/swagger-ui.html