pontuss 2020-04-11
号称全世界最流行的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;