SpringBoot 集成Swagger
Swagger 可以使你的restful接口自动生成接口文档,方便查看与测试,下面是一些具体步骤:
1、引入swagger相关依赖
<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、添加配置类
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//选择controller包
.apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//自定义信息可按需求填写
.title("API")
.description("接口文档")
.termsOfServiceUrl("http://localhost/web/")
.contact(new Contact("author", "", ""))
.version("1.0")
.build();
}
}
3、常用的一些注解
最常用的5个注解 主要用来对接口或参数做备注信息
@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiProperty:用对象接收参数时,描述对象的一个字段
4、注解使用demo
@Api(value="用户模块")
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@ApiOperation(value = "根据用户id查询用户")
@GetMapping("find/{id}")
public User findById(@ApiParam Integer id) {
User user = userService.findById(id);
return user;
}
}
5、启动和访问
启动application 并访问http://localhost:8088/swagger-ui.html,根据自身项目地址而定
6、常见问题
访问swagger-ui.html时,弹出错误提示框
Unable to infer base url.
This is common when using dynamic servlet registration or when the API is behind an API Gateway.
The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/.
Please enter the location manually: