Swagger
- 号称世界上最流行的Api框架
- RestFul Api 文档在线自动生成工具
- 直接运行、在线测试Api接口
在项目中是Swagger需要springfox
- swagger2
- ui
SpringBoot继承Swagger
依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
swaggerConfig
2.1 默认
@Configuration
@EnableSwagger2
public class SwaggerConfig {
}
2.2 修改默认的docket的bean信息,
@Configuration
@EnableSwagger2
public class SwaggerConfig {
// 修改默认的docket的bean信息,
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
}
private ApiInfo apiInfo(){
// 作者信息
Contact contact = new Contact("无敌我", "无", "无");
return new ApiInfo("无敌我的测试文档",
"用来测试swagger",
"1.0",
"https://www.baidu.com",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0", new ArrayList());
}
}
2.2 配置扫描方式–包扫描+过滤+是否启用
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.select().apis(RequestHandlerSelectors
// 配置包扫描
.basePackage("com.xusx.springboot.controlle")).build();
}
// 过滤
Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.xusx.springboot.controlle"))
// 只扫描带xusx的请求
.paths(PathSelectors.ant("/xusx/**"))
// 是否启用
enable(boolean )
.build();
根据生产环境还是发布环境去启用swagger
spring
profiles:
active: dev
@Bean
public Docket docket(Environment environment){
Profiles profiles=Profiles.of("dev");
boolean b = environment.acceptsProfiles(profiles);
System.out.println("---------------:"+b);
}
2.3分组----增加多个docket设置groupName
@Bean
public Docket docket(Environment environment){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.xusx.springboot.controlle")).build().
groupName("B"); // 分组
}
@Bean
public Docket docket1(Environment environment){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.xusx.springboot.controlle")).paths(PathSelectors.ant("/xusx/**")).build().
groupName("A"); // 分组
}
2.4Models 实体信息 ApiModel、ApiModelProperty
@ApiModel("登录用户")
public class Users {
private int id;
@ApiModelProperty("用户名")
private String username;
@ApiModelProperty("密码")
private String password;
private String role;
2.5@ApiOperation(“xxxxx”) 、 @ApiParam(“XXX”)
@ApiOperation:用在方法上,给方法加文档注释
@ApiParam: 用在参数
注:
get、post参数非实体时,添加@RequestParam**
public Users getUser(@RequestParam @ApiParam("用户名") String username){
启动报错
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException