swagger2的配置
package com.itcodai.course01.Swagger2Test;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket creatRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
//指定构建api文档的详细信息的方法:apiInfo()
.apiInfo(apiInfo())
.select()
//指定要生成api接口的包路径,这里把controller作为包路径,生成controller中的所有接口
.apis(RequestHandlerSelectors.basePackage("com.itcodai.course01.Swagger2Test"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//设置页面标题
.title("Spring Boot集成Swagger2接口总览")
//设置接口描述
.description("跟学spring boot")
//设置联系方式
.contact("sss," + "xxxxxxxxxx")
//设置版本
.version("1.0")
//构建
.build();
}
}
实体类注解
package com.itcodai.course01.Swagger2Test;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "用户实体类")
public class User {
@ApiModelProperty(value = "用户唯一标识")
private Long id;
@ApiModelProperty(value = "用户姓名")
private String username;
@ApiModelProperty(value = "用户密码")
private String userPassword;
//省略构造方法,set和get方法
- 解释@ApiModel* 和 @ApiModelProterty 注解
@ApiModel 注解用于实体类,表示对类进行说明,用于参数用实体类接收。
@ApiModelProperty 注解用于类中属性,表示对 model 属性的说明或者数据操作更改。
Controller类中的注解
package com.itcodai.course01.Swagger2Test;
import com.itcodai.course01.jsonTest.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@EnableSwagger2
@RestController
@RequestMapping("/swagger")
@Api(value = "Swagger2 在线接口文档")
public class TestController2 {
@GetMapping("/get/{id}")
@ApiOperation(value = "根据用户唯一标识获取用户信息")
public JsonResult<User> getUserInfo(@PathVariable @ApiParam(value = "用户唯一标识") Long id) {
//模拟数据库中根据id获取User信息
User user = new User(id, "xxx", "123432423");
return new JsonResult(user);
}
}
- @Api 、 @ApiOperation 和 @ApiParam 注解。
@Api 注解用于类上,表示标识这个类是 swagger 的资源。
@ApiOperation 注解用于方法,表示一个 http 请求的操作。
@ApiParam 注解用于参数上,用来标明参数信息。
实践中出现的错误
出现的错误:http://localhost:8001/swagger-ui.htm没有出现新增的接口 ,且程序没有报错
原因:最开头swagger2配置中的23行代码
.apis(RequestHandlerSelectors.basePackage(“com.itcodai.course01.Swagger2Test”))
引号包含的部分为java中包路径,即将该包中文件形成api。而路径错误导致swagger2 没有找到接口。
解决方法:每个类第一行就是该类的包路径,直接粘贴复制可以防止错误