swagger2可以直接生成文档,避免手写接口文档的麻烦和易错性。这里我们用springboot整合swagger2,做个demo。
项目pom.xml引入swagger2依赖
<!-- swagger2依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
使用@Configuration,注入bean
@Configuration
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.swag"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger2接口文档")
.description("简单优雅的restfun风格,http://blog.csdn.net/saytime")
.termsOfServiceUrl("http://blog.csdn.net/saytime")
.version("1.0")
.build();
}
}
swagger2注解说明
swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。
- @Api:修饰整个类,描述Controller的作用
- @ApiOperation:描述一个类的一个方法,或者说一个接口
- @ApiParam:单个参数描述
- @ApiModel:用对象来接收参数
- @ApiProperty:用对象接收参数时,描述对象的一个字段
- @ApiResponse:HTTP响应其中1个描述
- @ApiResponses:HTTP响应整体描述
- @ApiIgnore:使用该注解忽略这个API
- @ApiError :发生错误返回的信息
- @ApiImplicitParam:一个请求参数
- @ApiImplicitParams:多个请求参数
Application启用swagger2
@SpringBootApplication
@EnableSwagger2
public class SwagApplication {
public static void main(String[] args) {
SpringApplication.run(SwagApplication.class, args);
}
}
接口类
//接口名称
@Api("首页接口")
@RestController
@RequestMapping("/index")
public class IndexController {
@ApiOperation(value="hello接口",notes="测试hello接口")
@ApiParam("没有参数")
@RequestMapping(value="/hello",method=RequestMethod.GET)
public String hello() {
return "hello world";
}
//说明接口功能
@ApiOperation(value="保存用户数据,添加用户",notes="根据用户名和密码,添加用户")
//说明接口接收参数名称,是否必填,数据类型等
@ApiImplicitParams({
@ApiImplicitParam(name="username",value="用户名",required=true,dataType="String",paramType="path"),
@ApiImplicitParam(name="password",value="密码",required=true,dataType="String",paramType="path")
})
//说明返回代码意思
@ApiResponses({
@ApiResponse(code=502,message="发生异常"),
@ApiResponse(code=501,message="参数出错")
})
@RequestMapping(value="/saveUser/{username}/{password}",method=RequestMethod.POST)
public String saveUser(@PathVariable("username")String userName,@PathVariable("password")String password) {
return "hello world:"+userName;
}
}
application.yml设置swagger2访问根路径
启动服务器,访问http://localhost:8761/swag/swagger-ui.html
这样就可以查看接口文档了,但是如果网址让别人知道,不用鉴权就可以登录查看接口文档。这里我们结合下spring security oauth2,实现鉴权查看接口文档,下次再贴代码。