您的位置:首页 > 编程语言 > Java开发

spring-boot整合swagger生成在线api文档

2018-02-21 18:13 1231 查看
参考链接:https://www.cnblogs.com/luoluocaihong/p/7106276.html

最近用springboot构建rest接口,考虑到最方便的验证接口,想到了引入swagger。

基本的步骤大致如下:

1.pom中引入swagger依赖:

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>


2.创建swagger的配置类:

package com.coder520.mamabike.common.swagger;

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 createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.coder520.mamabike"))
.paths(PathSelectors.any())
.build();
}

private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("码码共享单车API文档")
.version("1.0")
.build();
}

}


然后在controller层的方法中添加注解

比如这样:

@ApiOperation(value="短信验证码",notes = "根据用户手机号码发送验证码",httpMethod = "POST")
@ApiImplicitParam(name = "user",value = "用户信息 包含手机号码",required = true,dataType = "User")
@RequestMapping("/sendVercode")
public ApiResult sendVercode(@RequestBody User user,HttpServletRequest request){
ApiResult<String> resp = new ApiResult<>();

try {
if(StringUtils.isEmpty(user.getMobile())){
throw new MaMaBikeException("手机号码不能为空");
}
userService.sendVercode(user.getMobile(),getIpFromRequest(request));
resp.setMessage("发送成功");
} catch (MaMaBikeException e) {
resp.setCode(e.getStatusCode());
resp.setMessage(e.getMessage());
} catch (Exception e) {
log.error("Fail to update user info", e);
resp.setCode(Constants.RESP_STATUS_INTERNAL_ERROR);
resp.setMessage("内部错误");
}

return resp;
}


然后访问http://localhost:8080/swagger-ui.html这个路径。

中间可能会出现json的错误,就是你项目中采用的是fastjson,出现错误提示

fetching resource list: http://localhost:8080/v2/api-docs; Please wait.


解决方法自行百度把。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: