目录
1、添加依赖
2、添加配置文件resources\config\swagger.properties
3、编写Swagger3Config配置类
4、编写Ctronller类
5、启动访问地址:
6、Swagger3常用注解说明
io.springfox
springfox-boot-starter
3.0.0
com.github.xiaoymin
swagger-bootstrap-ui
1.8.5
swagger.documentation-type=oas_30
swagger.base-package=com.example.demo.db.controller
swagger.api-info.title=demo_springboot
swagger.api-info.description=xxx
swagger.api-info.contact.name=JsonFling
[email protected]
swagger.api-info.contact.url=广东深圳
package com.example.demo.db.config;
import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.context.annotation.*;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.*;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
/**
* 描述: 单独定义 Swagger 配置类 profile 中包含 dev,sit,uat 任意一个时才会启动 Swagger (即生产环境不启动 Swagger) 环境变量
* SPRING_PROFILES_ACTIVE=dev/sit/uat 才启用该配置
*/
@Configuration
//@Profile({"dev", "test", "uat"})
@EnableOpenApi//会自动开启配置,启动类不需要加任何注解
@EnableSwaggerBootstrapUI//访问美化,方便查看调试
public class Swagger3Config {
/**
* @return Docket是swagger全局配置对象
*/
@Bean
public Docket createApi(SwaggerProperties properties) {
return new Docket(properties.getDocumentationType().value)
.apiInfo(createApiInfo(properties))
.select()
// 指定扫描的包,不指定会扫描出 spring 框架的接口,指定错误会导致接口扫描不出来
.apis(RequestHandlerSelectors
.basePackage(properties.getBasePackage()))
.paths(PathSelectors.any())
.build()
.globalRequestParameters(getGlobalRequestParameters())//加入通用入参
.globalResponses(HttpMethod.POST, getGlobalResonseMessage());//post方法加入通用响应头
}
/**
* API 文档基础信息,包括标题、联系人等
* @return ApiInfo
*/
private ApiInfo createApiInfo(SwaggerProperties properties) {
SwaggerApiInfo apiInfoMeta = properties.getApiInfo();
SwaggerApiInfoContact contactMeta = apiInfoMeta.getContact();
Contact contact = new Contact(contactMeta.getName(), contactMeta.getUrl(), contactMeta.getEmail());
return new ApiInfoBuilder()
.title(apiInfoMeta.getTitle())
.description(apiInfoMeta.getDescription())
.contact(contact)
.build();
}
//定义文档类型,配置文件配置
public enum DocumentationTypeMode {
/**
* SWAGGER_12
*/
SWAGGER_12(DocumentationType.SWAGGER_12),
/**
* SWAGGER_2
*/
SWAGGER_2(DocumentationType.SWAGGER_2),
/**
* OAS_30
*/
OAS_30(DocumentationType.OAS_30);
private final DocumentationType value;
DocumentationTypeMode(DocumentationType value) {
this.value = value;
}
}
@Component
@PropertySource(value = "classpath:/config/swagger.properties", ignoreResourceNotFound = true, encoding = "UTF-8")
@ConfigurationProperties(prefix = "swagger")
public static class SwaggerProperties {
private DocumentationTypeMode documentationType = DocumentationTypeMode.OAS_30;
private String basePackage = "com.example.demo.db.controller";
private SwaggerApiInfo apiInfo = new SwaggerApiInfo();
public DocumentationTypeMode getDocumentationType() {
return documentationType;
}
public void setDocumentationType(DocumentationTypeMode documentationType) {
this.documentationType = documentationType;
}
public String getBasePackage() {
return basePackage;
}
public void setBasePackage(String basePackage) {
this.basePackage = basePackage;
}
public SwaggerApiInfo getApiInfo() {
return apiInfo;
}
public void setApiInfo(SwaggerApiInfo apiInfo) {
this.apiInfo = apiInfo;
}
}
//文档信息联系人实体类
public static class SwaggerApiInfoContact {
private String name;
private String url;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
//文档信息联系人实体类
public static class SwaggerApiInfo {
private String title;
private String description;
@NestedConfigurationProperty
private SwaggerApiInfoContact contact;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public SwaggerApiInfoContact getContact() {
return contact;
}
public void setContact(SwaggerApiInfoContact contact) {
this.contact = contact;
}
}
//生产通过接口入参
private List getGlobalRequestParameters() {
List parameters = new ArrayList<>();
parameters.add(new RequestParameterBuilder()
.name("appid")
.description("平台id")
.required(true)
.in(ParameterType.QUERY)
.query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
.required(false)
.build());
parameters.add(new RequestParameterBuilder()
.name("udid")
.description("设备的唯一id")
.required(true)
.in(ParameterType.QUERY)
.query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
.required(false)
.build());
parameters.add(new RequestParameterBuilder()
.name("version")
.description("客户端的版本号")
.required(true)
.in(ParameterType.QUERY)
.query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
.required(false)
.build());
return parameters;
}
//生成通用响应信息
private List getGlobalResonseMessage() {
List responseList = new ArrayList<>();
responseList.add(new ResponseBuilder()
.code("404")
.description("找不到资源")
.build());
responseList.add(new ResponseBuilder()
.code("0")
.description("成功")
.build());
responseList.add(new ResponseBuilder()
.code("10")
.description("系统异常")
.build());
responseList.add(new ResponseBuilder()
.code("20")
.description("参数错误")
.build());
responseList.add(new ResponseBuilder()
.code("30")
.description("系统异常")
.build());
//或者通过枚举类添加
// for (ResponseStatusEnum value:ResponseStatusEnum.values()) {
// String code = String.valueOf(value.getCode());
// String message =value.getMessage();
// responseList.add(new ResponseBuilder().code(code).description(message);
// }
return responseList;
}
}
package com.example.demo.db.controller;
import com.example.demo.db.domain.Student;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
@Api(tags = "学生信息Controller")
@RestController
@RequestMapping(value = "/Student",method = RequestMethod.GET)
public class StudentController{
@ApiOperation(value ="学生信息查询findAllStudent接口",notes = "注意点说明:接口通过id获取用户的详细信息,id必须传递")
@ApiImplicitParams({
@ApiImplicitParam(name = "sid", value = "用户id", required = true, dataType = "String", paramType = "query",defaultValue = "01"),
@ApiImplicitParam(name = "sname", value = "用户姓名", required = false, dataType = "String", paramType = "query",defaultValue = "赵雷"),
})
@RequestMapping(value = "/findAllStudent")
public Student findAllStudent(String sid,String sname){
return null;
}
}
http://localhost:8011/doc.html (加入UI优化依赖的访问路径)
http://localhost:8011/swagger-ui/index.html (原始路径)
@Api:用在请求的类上,说明该类的作用
参数:
tags:说明这个类的作用
value:这个参数没有什么意义,不需要配置
@Api(tags = "学生信息Controller")
@ApiOperation:用在请求的方法上,说明方法的作用
参数:
value:说明方法的作用
notes:方法的备注说明
@ApiOperation(value ="学生信息查询findAllStudent接口",notes = "注意点说明:接口通过id获取用户的详细信息,id必须传递")
@ApiImplicitParams和@ApiImplicitParam,和@ApiParam
(1) @ApiImplicitParams:用在请求的方法上,包含一组参数说明
(2)@ApiImplicitParams:用在 @ApiImplicitParams 注解中,指定一个请求参数的配置信息
参数:
name:参数名
value:参数的汉字说明、解释
required:参数是否必须传
paramType:参数放在哪个地方
· header --> 请求参数的获取:@RequestHeader
· query --> 请求参数的获取:@RequestParam
· path(用于restful接口)--> 请求参数的获取:@PathVariable
· body(不常用)
· form(不常用)
dataType:参数类型,默认String,其它值dataType="Integer"
defaultValue:参数的默认值
(3)@ApiParam:用在方法参数里,指定对应请求参数的配置信息
@ApiImplicitParams({
@ApiImplicitParam(name = "sid", value = "用户id", required = true, dataType = "String", paramType = "query",defaultValue = "01"),
@ApiImplicitParam(name = "sname", value = "用户姓名", required = false, dataType = "String", paramType = "query",defaultValue = "赵雷"),
})
findAllStudent(@ApiParam(value = "id",name="id",required = true,defaultValue = "01") String id){
@ApiModel和@ApiModelProperty
(1)@ApiModel:用于响应类上,表示一个返回响应数据的信息
(这种一般用在post创建的时候,使用@RequestBody这样的场景,
请求参数无法使用@ApiImplicitParam注解进行描述的时候)
(2)@ApiModelProperty:用在属性上,描述响应类的属性
@ApiModel(value = "Student实体类",description = "学生实体对象")
@Data
public class Student implements Serializable {
@ApiModelProperty("学生id")
private String sid;
@ApiModelProperty("学生姓名")
private String sname;
@ApiModelProperty("学生年龄")
private Date sage;
@ApiModelProperty("学生性别")
private String ssex;
}
@ApiResponses和@ApiResponse
(1)@ApiResponses:用于请求的方法上,表示一组响应
(2)@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类
@ApiResponses({
@ApiResponse(code=400,message="请求参数没填好"),
@ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})