一、导入依赖
<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>
二、创建swagger配置
在Application.java同级,创建Swagger2的配置类Swagger2:
@Configuration
@EnableSwagger2
public class Swagger2 {
@Value("${swagger.enable}")
private Boolean enable;
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Api接口")
.description("Api接口的描述")
.termsOfServiceUrl("http://www.baidu.com/")
.version("1.0")
.build();
}
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.xxx.xxx.controller"))
.paths(PathSelectors.any())
.build()
.enable(enable);
}
}
@ Configuration:spring boot 加载配置。
@EnableSwagger2:启用Swagger2。
createRestApi():创建Api的基本信息。RequestHandlerSelectors.basePackage是通过扫描该路径下的所有Controller定义的API,并产生文档内容(除了被@ApiIgnore指定的请求)。
.enable(enable):通过配置文件控制swagger2是否启用。在配置文件中配置swagger.enable为“true”或“false”。一般正式环境会关闭swagger功能。
三、配置资源路径
如果继承了WebMvcConfigurationSupport,则需要重新指定静态资源(不配置的话会报No mapping for GET /swagger-ui.html错误):
@Configuration
public class CorsConfig extends WebMvcConfigurationSupport {
private MyInterceptor myInterceptor;
@Autowired
public CorsConfig (MyInterceptor myInterceptor){
this.myInterceptor = myInterceptor;
}
// 注册过滤器
@Bean
public FilterRegistrationBean<RepeatedlyReadFilter> repeatedlyReadFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
RepeatedlyReadFilter repeatedlyReadFilter = new RepeatedlyReadFilter();
registration.setFilter(repeatedlyReadFilter);
registration.addUrlPatterns("/*");
return registration;
}
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**");
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(
"classpath:/static/");
registry.addResourceHandler("swagger-ui.html").addResourceLocations(
"classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
}
四、添加接口文档内容
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import com.xyf.scriptkill.util.RestMessage;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
@Api(tags="测试控制器")
@RestController
public class TestController {
@ApiOperation(value="测试get", notes="")
@ApiImplicitParams({
@ApiImplicitParam(name="name",value="姓名",required=true,paramType="query"),
@ApiImplicitParam(name="address",value="地址",required=true,paramType="query"),
})
@GetMapping("/api/gettest")
public RestMessage getTest(
@RequestParam(value = "name", required = true) String name,
@RequestParam(value = "address", required = true) String address
){
RestMessage restMessage = new RestMessage();
restMessage.setSuccess(true);
restMessage.setMessage("返回成功!");
restMessage.setData(null);
restMessage.setCode(HttpStatus.HTTP_OK);
return restMessage;
}
@ApiOperation(value="测试post")
@ApiResponses({
@ApiResponse(code=400,message="请求参数没填好"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
@ApiImplicitParams({
@ApiImplicitParam(name="jsonParams",value="json",paramType="body")
})
@PostMapping("/api/posttest")
public RestMessage postTest(
@RequestBody JSONObject jsonParams
){
RestMessage restMessage = new RestMessage();
restMessage.setCode(HttpStatus.HTTP_OK);
restMessage.setData(jsonParams);
restMessage.setMessage("返回成功!");
restMessage.setSuccess(true);
return restMessage;
}
}
-
@Api:"用在Conntroller类上,表示对类的说明:
- tags= 说明该类的作用,可以在UI界面上看到配置的内容。
- value= 在UI界面上看不到到,可不配置。
-
@ApiOperation:用在Conntroller类的方法上,说明方法的用途、作用:
- value= 说明方法的用途、作用。
- notes= 方法的备注说明。
-
@ApiImplicitParams: 用在Conntroller类的方法上,表示一组参数说明:
-
@ApiImplicitParam: 用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
- name: 参数名称。
- value: 参数的汉字说明、解释。
- required: 参数是否必须项。
-
paramType: 参数放在哪个地方。
- header:参数在request header获取,@RequestHeader。
- query:请求参数的获取,@RequestParam。
- path:以地址的形式提交,@PathVariable。
- body:请求参数的获取,@RequestBody,仅支持Post。
- form:以form表单的形式提交 仅支持Post。
- dataType:参数类型,默认String,其它值如dataType="Integer"。
- defaultValue:参数的默认值。
-
@ApiImplicitParam: 用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
-
@ ApiResponses: 用在Conntroller类的方法上,表示一组响应:
-
@ ApiResponse: 用在@ApiResponses中,一般用于表达一个错误的响应信息
- code: 数字,例如400。
- message: 信息内容。
-
response: 抛出异常的类。
@ ApiResponses
-
@ ApiResponse: 用在@ApiResponses中,一般用于表达一个错误的响应信息
-
@ ApiModel: 用于响应类上,表示一个返回响应数据的信息:
- @ ApiModelProperty: 用在属性上,描述响应类的属性。
import cn.hutool.json.JSONObject;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
@ApiModel(description= "返回响应数据")
public class RestMessage implements Serializable {
@ApiModelProperty(value = "是否成功")
private boolean success;
@ApiModelProperty(value = "返回对象")
private JSONObject data;
@ApiModelProperty(value = "状态码")
private Integer code;
@ApiModelProperty(value = "返回信息")
private String message;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public JSONObject getData() {
return data;
}
public void setData(JSONObject data) {
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
ok,启动Spring boot,输入http://localhost:8081/swagger-ui.html
swagger