前后端分离项目中,对于API的管理一直很头疼,swagger2即可以解决这个问题!
1)引入依赖:
<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>
2)***Swagger配置类
@Configuration
public class Swagger2 {
@Value("${swagger2.enable}")
private boolean enable;
/**
* 在Docket创建中,通过groupName进行分组,paths属性进行过滤,apis属性可以设置扫描包,或者通
* 过注解的方式标识;通过enable属性,可以在application-{profile}.properties文件中设置相
* 应值,主要用于控制生产环境不生成接口文档
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// .apis(RequestHandlerSelectors.basePackage("com.xxx.Controller")) 只扫描Controller
// 方法上有ApiOperation注解的才被扫描
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
// .paths(PathSelectors.regex("/user.*")) 可以使用正则过滤
.enable(enable)
.build();
}
//包括 标题、描述、服务网址、联系人、版本等信息
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("XXX系统平台API接口文档")
.description("接口文档")
.termsOfServiceUrl("")
.version("1.0")
.build();
}
}
3)spring boot主启动类加上@EnableSwagger2注解
// Application.class加上@EnableSwagger2注解表示开启Swagger
@SpringBootApplication
@EnableSwagger2
public class SpringbootSwagger2Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootSwagger2Application.class, args);
}
}
4)restful接口
/**
* 根据ID和name查询用户
* @param id,name
* @return
*/
@ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path"),
@ApiImplicitParam(name = "name", value = "用户名", required = true, dataType = "String", paramType = "path")
})
@GetMapping("user/{id}/{name}")
public User getUserByIdAndName (@PathVariable(value = "id") Integer id, @PathVariable(value = "name") String name){
// xxx
}
项目启动后,访问路径为:IP:端口 + swagger-ui.html
同时,开放以下几个路径不做拦截:
/swagger-ui.html
/swagger-resources
/swagger-resources/configuration/security
/swagger-resources/configuration/ui
/v2/api-docs
/webjars/springfox-swagger-ui/**