1. 导入Pom包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
2. 编写配置文件
在application.properties
中设置swagger.enable
为true即可开启swagger,在生产环境设置为false则可关闭swagger
@Configuration
@EnableSwagger2
@ConditionalOnProperty(value = "swagger.enable", havingValue = "true")
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("cn.ntshare.laboratory.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
// 填写文档开发者信息
Contact contact = new Contact("3795", "https://www.ntshare.cn", "seven.iwi@gmail.com");
return new ApiInfoBuilder()
.title("Swagger示例标题")
.description("这是Swagger示例描述")
.contact(contact)
.version("1.0.0")
.build();
}
}
3. 测试
3.1 User.java
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class User {
@ApiModelProperty(value = "ID", example = "132")
private String id;
@ApiModelProperty(value = "用户名", example = "小明")
private String username;
}
- @ApiModelProperty作用于对象属性上,value声明该字段的含义,example将在Swagger中返回一个示例值
3.2 TestController.java
@RestController
@RequestMapping("/test")
@Slf4j
@Api(tags = "测试接口")
public class TestController {
@GetMapping("/methodA")
@ApiOperation("测试Swagger功能")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "id", defaultValue = "111", required = false, paramType = "query"),
@ApiImplicitParam(name = "username", value = "用户名", defaultValue = "Tom", required = false, paramType = "query"),
})
@ApiResponses({
@ApiResponse(code = 200, message = "请求成功", response = User.class)
})
public User test(@RequestParam(value = "id", defaultValue = "111", required = false) String id,
@RequestParam(value = "username", defaultValue = "Tom", required = false) String username) {
return new User(id, username);
}
}
- @Api作用了类上,作为协议集描述(控制器的描述)
- @ApiOperation,描述该接口方法
- @ApiImplicitParams,参数集
- @ApiImplicitParam,参数的具体描述
- @ApiResponses,接口的返回对象集
- @ApiResponse,接口的返回值模型,code:请求返回值,message:请求返回消息,response:返回值中的类型
4. 访问
运行项目,访问地址为:ip:post/项目路径前缀/swagger-ui.html
,
如:http://localhost:8080/laboratory/swagger-ui.html
特别注意,如果配置了项目路径前缀的话,一定不要忘了!