#SpringBoot集成Swagger
##1、用途
- Swagger是一个简单但功能强大的API表达工具
- 使用Swagger生成工具,可以得到交互式文档
##2、集成
- maven引入依赖,配置Swagger,设置静态资源映射
###2.1、引入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
###2.2、设置静态资源映射
- xxxApplication启动类
- 不配值映射/,springmvc默认执行DispatcherServlet,就会去执行控制器,而不是静态资源
/**
* SpringBoot方式启动类
*
*/
@SpringBootApplication
public class SwaggerApplication extends WebMvcConfigurerAdapter {
protected final static Logger logger = LoggerFactory.getLogger(SwaggerApplication .class);
/**
* 增加swagger的支持
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (gunsProperties.getSwaggerOpen()) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
public static void main(String[] args) {
SpringApplication.run(SwaggerApplication .class, args);
logger.info("SwaggerApplication is success!");
}
}
###2.3、配置Swagger
/**
* swagger配置类
*
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig{
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) //这里采用包含注解的方式来确定要显示的接口
//.apis(RequestHandlerSelectors.basePackage("com.modular.controller")) //这里采用包扫描的方式来确定要显示的接口
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("标题")
.description("描述")
.termsOfServiceUrl("http://git.oschina.net/naan1993/guns")
.contact("作者")
.version("版本号")
.build();
}
}
##3、使用
- @ApiOperation:用在方法上,说明方法的作用
- @ApiImplicitParams:用在方法上包含一组参数说明
- @ApiImpllicitParam:用在@ApilmplicitParams注解中,指定一个请求参数的各个方面
- paramType:参数放在哪个地方
headers——>请求参数的获取:@RequestHeader
query——>请求参数的获取:@RequestParam
path(用于restful接口)——>请求参数的获取:@PathVariable
body(@RequestBody)
form(表单提交)
- name:参数名
- dataType:参数类型
- required:参数是否必传
- value:参数的意思
- defaultValue:参数的默认值
/**
* demo
*/
@ApiOperation(value = "接口名称",notes = "描述",tags = {"分组/标签","tags2"},response = UserDto.class"/返回值")
@ApiImplicitParams({
@ApiImplicitParam(name="参数字段名",value = "描述",required = true,dataType = "String",paramType = "query"),
@ApiImplicitParam(name="xxx",value = "模块名称",required = true,dataType = "String",paramType = "path"),
})
public Object add(@RequestParam String 参数字段名,
@PathVariable String xxxx){
...
}