spring-boot整合swagger生成線上api文件
阿新 • • 發佈:2019-02-08
基本的步驟大致如下:
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;
}
中間可能會出現json的錯誤,就是你專案中採用的是fastjson,出現錯誤提示
fetching resource list: http://localhost:8080/v2/api-docs; Please wait.
解決方法自行百度把。