Swagger入门
为什么要学习swagger?swagger是什么?
为了分离前后端交互,而且在接口文档方面更具有实时性,能够及时更新接口文档,并且可以把接口和数据通过视图ui的方式呈现出来。而swagger就是能够做这个文档的工具,能实时更新。对于swagger的配置文件就需要分析源码,其实都是ApiInfo里面的变量,然后我们只需要使用Docket来初始化,加载我们所想要的info就可以了。
**扫描包、过滤:**还有一些拓展的功能,比如说扫描包,需要调用select()方法来确定使用的是什么选择器,然后给选择器加上一些Selector来确定扫描什么包。也可以过滤某些路径。所以这里也是链式编程。
判断环境:另外就是如何确定当前的配置环境是不是dev,我们可以通过传入Environment变量来判断,并且通过Profiles.of来查找是不是存在这样的配置环境。
注释与测试:这个可能是swagger比较强大的地方我们可以通过@Apixxx()来做各种注释,最后这些注释都会展现到文档上面去。而且文档可以直接发送请求来测试接口得到的数据,并且能清晰知道出现什么样的错误。
代码(依赖导入)
<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)
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket(Environment environment){
//判断现在使用的是不是dev环境
Profiles profiles=Profiles.of("dev");
boolean flag = environment.acceptsProfiles(profiles);
// 是否开启swagger,开启扫描包
return new Docket(DocumentationType.SWAGGER_2)
//设置html的信息
.apiInfo(apiInfo())
.enable(true)
.select()
//扫描包,来确定有什么接口
.apis(RequestHandlerSelectors.none())
//过滤
.paths(PathSelectors.ant("com/kuang/**"))
.build();
}
@Bean
public ApiInfo apiInfo(){
//测试
Contact contact = new Contact("好人", "#", "ssss@qq.com");
ApiInfo info = new ApiInfo("Api Documentation",
"我是好人",
"1.0",
"#",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<>()
);
return info;
}
}
代码(HelloController)
@RestController
public class HelloController {
@RequestMapping("/test")
public String test(){
return "test";
}
@ApiOperation("特殊用户方法")
@RequestMapping("/user")
public User user(@ApiParam("用户信息") User user){
return user;
}
}
代码(注释)
@ApiModelProperty("用户名")
private String username;
@ApiModelProperty("密码")
private String password;