Reference link: https://www.cnblogs.com/luoluocaihong/p/7106276.html
Recently, I used springboot to build the rest interface. Considering the most convenient verification interface, I thought of introducing swagger.
The basic steps are roughly as follows:
1. Swagger dependency introduced in pom:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
2. Create swagger configuration class:
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();
}
}
Then add annotations in the process layer controller
like this:
@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;
}
Then visit http: // localhost: 8080 / swagger-ui.html this path.
There may be a json error in the middle, that is, your project uses fastjson, and an error message appears
fetching resource list: http://localhost:8080/v2/api-docs; Please wait.
The solution is Baidu.