Swagger和springboot整合
Swagger
号称全世界最流行的api框架;
RestFul Api 文档在线自动生成工具=>Api文档与API定义同步更新
配置
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 --><dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version></dependency>?<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui --><dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version></dependency>?
简单的更改文档信息,主要看源码
@Configuration@EnableSwagger2 //开启swagger2public class SwaggerConfig {? @Bean//配置swagger的Docket的bean实例 public Docket docket(){ return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()); }? //重写apiInfo private ApiInfo apiInfo(){ Contact contact = new Contact("", "", ""); return new ApiInfo("Api Documentation", "Api Documentation", "1.0", "urn:tos", contact, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList());? }}
配置扫描接口
@Configuration@EnableSwagger2 //开启swagger2public class SwaggerConfig {? @Bean//配置swagger的Docket的bean实例 public Docket docket(){ return new Docket(DocumentationType.SWAGGER_2) .select() //RequestHandlerSelectors 配置要扫描接口的方式 //basePackage 指定要扫描的包 .apis(RequestHandlerSelectors.basePackage("com.lt.controller")) //过滤路径 //ant()过滤的路径 .paths(PathSelectors.ant("/")) .build(); }?}
题目
我们只希望swagger在生产使用,在发布不使用。
使用 .enable() 判断
@Configuration@EnableSwagger2 //开启swagger2public class SwaggerConfig {? @Bean//配置swagger的Docket的bean实例 public Docket docket(Environment environment){ Profiles dev = Profiles.of("dev"); boolean b = environment.acceptsProfiles(dev);//判断是否是当前文件 return new Docket(DocumentationType.SWAGGER_2) .enable(b); }?}
分组
组名
.groupName("A")
如何分组:创建多个Docket即可如
@Configuration@EnableSwagger2 //开启swagger2public class SwaggerConfig {? @Bean//配置swagger的Docket的bean实例 public Docket docket1(){ return new Docket(DocumentationType.SWAGGER_2) .groupName("A"); }@Bean//配置swagger的Docket的bean实例 public Docket docket2(){ return new Docket(DocumentationType.SWAGGER_2) .groupName("B"); }@Bean//配置swagger的Docket的bean实例 public Docket docket3(){ return new Docket(DocumentationType.SWAGGER_2) .groupName("C"); }?}?
接口注释
只要我们的接口中返回值有实体类就会存在到swagger。
@GetMapping("/user") public User user(){ return new User(); }
@ApiModel("用户") 给实体类加标注
@ApiModel("用户")public class User { public String userName; public String password;}
@ApiOperation("111111") 给方法加注释
@ApiParam("2222")给参数加注释
@ApiOperation("111111") public String user1( @ApiParam("2222") String userName ){ return "new User()"; }}
@ApiModelProperty("用户名字") 给实体加注释
@ApiModelProperty("用户名字") public String userName;
相关推荐
SAMXIE 2020-11-04
XuDanT 2020-09-16
permanent00 2020-09-15
哈嘿Blog 2020-09-08
Qizonghui 2020-08-02
莫问前程 2020-08-02
SAMXIE 2020-07-26
XuDanT 2020-07-24
莫问前程 2020-07-18
Qizonghui 2020-07-18
coolhty 2020-07-05
Qizonghui 2020-06-28
Qizonghui 2020-06-25
莫问前程 2020-06-22
SAMXIE 2020-06-14
莫问前程 2020-06-14
XuDanT 2020-06-07
qingjiuquan 2020-06-07
TimeMagician 2020-06-03