首先配置maven文件:
<!-- 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>
要使用Swagger,我们需要编写一个配置类-SwaggerConfig来配置 Swagger
package com.zs.swagger.config;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2 // 开启swagger2
public class SwaggerConfig {
}
访问测试 :http://localhost:8080/swagger-ui.html ,可以看到swagger的界面:
Swagger实例Bean是Docket,所以通过配置Docket实例来配置Swaggger:
@Bean //配置docket以配置Swagger具体参数
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2);
}
可以通过apiInfo()属性配置文档信息
//配置文档信息
private ApiInfo apiInfo() {
Contact contact = new Contact("赵 帅", "http://www.baidu.com", "930312043@qq.com");
return new ApiInfo(
"TestSpringboot", // 标题
"学习演示如何配置Swagger", // 描述
"v1.0", // 版本
"http://www.baidu.com", // 组织链接
contact, // 联系人信息
"Apach 2.0 许可", // 许可
"许可链接", // 许可连接
new ArrayList<>()// 扩展
);
}
@Bean //配置docket以配置Swagger具体参数
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
// .apis(RequestHandlerSelectors.any()) // 扫描所有的接口
.apis(RequestHandlerSelectors.basePackage("com.zs"))
.paths(PathSelectors.ant("/zs/**")) // 配置如何通过path过滤,即这里只扫描请求以/zs开头的接口
.build();
}
实体类的配置:并不是因为@ApiModel这个注解让实体显示在这里了,而是只要出现在接口方法的返回值上的实体都会显示在这里,而@ApiModel和@ApiModelProperty这两个注解只是为实体添加注释的。
package com.zs.swagger.pojo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel("用户实体(User)")
public class User {
@ApiModelProperty("用户名")
private String username;
@ApiModelProperty("密码")
private String password;
}
@RequestMapping("/getUser")
public User getUser() {
return new User();
}