Swagger2是一款restful接口文档在线生成和在线接口调试工具,Swagger2在Swagger1.x版本的基础上做了些改进,下面是在一个Spring Boot项目中引入Swagger2的简要示例。
一、在pom.xml添加如下maven依赖
<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>
二、Swagger配置类
package com.weidai.zm.zyq.config; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; /**
* @author : zhangyanqing
* @time : 2017/11/8
* @desc : Swagger2配置
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.weidai.zm.zyq.action"))
.paths(PathSelectors.any())
.build();
} private ApiInfo apiInfo(){
return new ApiInfoBuilder().title("Spring Boot中使用Swagger构建Rest Api")
.version("1.0").build();
}
}
三、SpringBoot启动类修改
package com.weidai.zm.zyq; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class SwaggerDemoApplication { public static void main(String[] args) {
SpringApplication.run(SwaggerDemoApplication.class, args);
}
}
四、接口注释示例
package com.weidai.zm.zyq.action; import com.weidai.zm.zyq.domain.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*; /**
* @author : zhangyanqing
* @time : 2017/11/8
* @desc : ${DESCRIPTION}
*/
@Api(value="/test", tags="测试接口模块")
@RestController
@RequestMapping("/test")
public class TestController {
@ApiOperation(value="展示首页信息", notes = "展示首页信息")
@GetMapping("/show")
public Object showInfo(){
return "hello world";
} @ApiOperation(value="添加用户信息", notes = "添加用户信息")
@ApiImplicitParam(name="user", value="User", required = true, dataType = "User")
@PostMapping("/addUser")
public Object addUser(@RequestBody User user){
return "success";
}
}
类、方法注解含义可自行参考官网