一.如何引入swagger2:
pom.xml文件中引入:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
如果遇见报错:
Failed to start bean ‘documentationPluginsBootstrapper’
这个问题解决办法是因为swagger依赖google的guava,而你当前项目的guava版本与之不匹配,而我因为使用当前最新的swagger2版本,我就将guava升到最新的版本
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>25.1-jre</version>
</dependency>
二.编写一个SwaggerConfig类:
@Configuration
@EnableWebMvc
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage("com.dh.xx.xx")).paths(PathSelectors.any()).build();
}
@SuppressWarnings("deprecation")
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("swagger-bootstrap-ui RESTful APIs").description("swagger-bootstrap-ui")
.termsOfServiceUrl("http://localhost:8080/").contact("developer@mail.com").version("1.0").build();
}
}
三.如果是springmvc项目的话 可以在:springmvc.xml 中加入
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
四.对应的接口应该如何编写
1.首先,入参尽量用对象来,不管是get还是post方法,还可以做一些封装。
如果未封装对象的话可以用:
@ApiImplicitParams({
@ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
@ApiImplicitParam(name="password",value="密码",required=true,paramType="form"))
})
@RequestMapping("get")
@ApiOperation(value = "值", httpMethod = "POST", notes = "信息.")
public DoResponse get(@RequestParam String mobile,@RequestParam String password) {
return null;
}
当然建议封装对象, 那就可以不用一大坨@ApiImplicitParams 而是可以用这个注解 :@ApiModelProperty 。
@PostMapping("req")
public void handleSyncAccount(@ModelAttribute Req req) {}
-- 分割 ---
@Data
public class Req extends PageQuery{
@ApiModelProperty(value = "商品类型ID")
private Long typeId;
}
2.对于返回值的处理:建议封装一个通用的返回对象如
@Data
public class RespDataT<T>{
public static final int Success = 1;
public static final int Error = 0;
private int status;
private T datas ;
private Object meta = "";
public RespDataT(T datas) {
this.datas = (T)datas;
this.status =Success;
}
public RespDataT(int status, T datas) {
this.status = status;
if(status == Success){
this.datas =(T) datas;
}else{
this.meta = datas;
}
}
public RespDataT(Exception e){
this.status = Error;
this.meta = e.getMessage();
}
}
五.如何访问:http://127.0.0.1:8082/项目名/swagger-ui.html#/