Swagger:RestFul Api文档在线自动生成工具,Api文档与API定义同步更新
Swagger访问地址:http://localhost:8080/swagger-ui.html
使用Swagger
1.导入依赖
<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>
2.编写SwaggerConfig类
@Configuration//表明这是一个配置类
@EnableSwagger2//开启Swagger服务
public class SwaggerConfig {
//配置多个分组:实现多个Docket实例
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2).groupName("B");
}
//配置了Swagger的Docket的Bean实例
@Bean
public Docket docket(Environment environment){
//设置要显示的Swagger环境
Profiles profiles = Profiles.of("dev","test");
//通过environment.acceptsProfiles()判断是否处于需要开启Swagger的环境
boolean flag = environment.acceptsProfiles(profiles);
System.out.println(flag);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("芈")//配置API文档分组
.enable(flag)
.select()
.apis(RequestHandlerSelectors.basePackage("com.mi.controller"))//basePackage:配置要扫描接口的包
// .paths(PathSelectors.ant("/mi/"))过滤什么路径
.build();
}
//配置apiInfo
private ApiInfo apiInfo(){
//作者信息
Contact contact = new Contact("芈", "https://blog.csdn.net/qq_42500503", "996489871@qq.com");
return new ApiInfo("芈的SwaggerAPI文档",
"自己选的路,怎么也要走完", "1.0",
"https://blog.csdn.net/qq_42500503", contact, "Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0", new ArrayList());
}
}
3.编写实体类
@ApiModel("用户类 ")//给实体类加注释
public class User {
@ApiModelProperty("用户ID")//给实体类属性加注释
private int id;
@ApiModelProperty("用户名称")
private String name;
@ApiModelProperty("用户密码")
private String password;
}//提供get和set方法
4.编写controller(在config配置了扫描包的位置后,Swagger会自动扫描包,根据GetMapping和PostMapping去显示接口方式)
@Api(tags = "Hello控制器")
@Controller
public class HelloController {
@GetMapping(value = "/hello")
@ResponseBody
public String hello(){
return "hello";
}
@PostMapping("/getUser")
@ResponseBody
@ApiOperation("获取用户")//给接口表明注释
public User getUser(){
User user = new User(1, "芈", "123456");
return user;
}
}
实现效果:
注意在项目上线前要把Swagger关闭,不然会导致接口暴露(方法见SwaggerConfig类中给enable()方法设置flag,根据环境开启和关闭Swagger)