0


Springboot集成Swagger3详细操作步骤

1、添加依赖

  1. <!-- 引入swagger3包 -->
  2. <dependency>
  3. <groupId>io.springfox</groupId>
  4. <artifactId>springfox-boot-starter</artifactId>
  5. <version>3.0.0</version>
  6. </dependency>
  7. <!-- 引入swagger-bootstrap-ui包,优化UI页面,可不加 -->
  8. <dependency>
  9. <groupId>com.github.xiaoymin</groupId>
  10. <artifactId>swagger-bootstrap-ui</artifactId>
  11. <version>1.8.5</version>
  12. </dependency>

2、添加配置文件resources\config\swagger.properties

  1. swagger.documentation-type=oas_30
  2. swagger.base-package=com.example.demo.db.controller
  3. swagger.api-info.title=demo_springboot
  4. swagger.api-info.description=xxx
  5. swagger.api-info.contact.name=JsonFling
  6. swagger.api-info.contact.email=jsonfling@xxxxxxxx.com
  7. swagger.api-info.contact.url=广东深圳

3、编写Swagger3Config配置类

  1. package com.example.demo.db.config;
  2. import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
  3. import org.springframework.boot.context.properties.ConfigurationProperties;
  4. import org.springframework.boot.context.properties.NestedConfigurationProperty;
  5. import org.springframework.context.annotation.*;
  6. import org.springframework.http.HttpMethod;
  7. import org.springframework.stereotype.Component;
  8. import springfox.documentation.builders.*;
  9. import springfox.documentation.oas.annotations.EnableOpenApi;
  10. import springfox.documentation.schema.ScalarType;
  11. import springfox.documentation.service.*;
  12. import springfox.documentation.spi.DocumentationType;
  13. import springfox.documentation.spring.web.plugins.Docket;
  14. import java.util.ArrayList;
  15. import java.util.List;
  16. import java.util.ResourceBundle;
  17. /**
  18. * 描述: 单独定义 Swagger 配置类 profile 中包含 dev,sit,uat 任意一个时才会启动 Swagger (即生产环境不启动 Swagger) 环境变量
  19. * SPRING_PROFILES_ACTIVE=dev/sit/uat 才启用该配置
  20. */
  21. @Configuration
  22. //@Profile({"dev", "test", "uat"})
  23. @EnableOpenApi//会自动开启配置,启动类不需要加任何注解
  24. @EnableSwaggerBootstrapUI//访问美化,方便查看调试
  25. public class Swagger3Config {
  26. /**
  27. * @return Docket是swagger全局配置对象
  28. */
  29. @Bean
  30. public Docket createApi(SwaggerProperties properties) {
  31. return new Docket(properties.getDocumentationType().value)
  32. .apiInfo(createApiInfo(properties))
  33. .select()
  34. // 指定扫描的包,不指定会扫描出 spring 框架的接口,指定错误会导致接口扫描不出来
  35. .apis(RequestHandlerSelectors
  36. .basePackage(properties.getBasePackage()))
  37. .paths(PathSelectors.any())
  38. .build()
  39. .globalRequestParameters(getGlobalRequestParameters())//加入通用入参
  40. .globalResponses(HttpMethod.POST, getGlobalResonseMessage());//post方法加入通用响应头
  41. }
  42. /**
  43. * API 文档基础信息,包括标题、联系人等
  44. * @return ApiInfo
  45. */
  46. private ApiInfo createApiInfo(SwaggerProperties properties) {
  47. SwaggerApiInfo apiInfoMeta = properties.getApiInfo();
  48. SwaggerApiInfoContact contactMeta = apiInfoMeta.getContact();
  49. Contact contact = new Contact(contactMeta.getName(), contactMeta.getUrl(), contactMeta.getEmail());
  50. return new ApiInfoBuilder()
  51. .title(apiInfoMeta.getTitle())
  52. .description(apiInfoMeta.getDescription())
  53. .contact(contact)
  54. .build();
  55. }
  56. //定义文档类型,配置文件配置
  57. public enum DocumentationTypeMode {
  58. /**
  59. * SWAGGER_12
  60. */
  61. SWAGGER_12(DocumentationType.SWAGGER_12),
  62. /**
  63. * SWAGGER_2
  64. */
  65. SWAGGER_2(DocumentationType.SWAGGER_2),
  66. /**
  67. * OAS_30
  68. */
  69. OAS_30(DocumentationType.OAS_30);
  70. private final DocumentationType value;
  71. DocumentationTypeMode(DocumentationType value) {
  72. this.value = value;
  73. }
  74. }
  75. @Component
  76. @PropertySource(value = "classpath:/config/swagger.properties", ignoreResourceNotFound = true, encoding = "UTF-8")
  77. @ConfigurationProperties(prefix = "swagger")
  78. public static class SwaggerProperties {
  79. private DocumentationTypeMode documentationType = DocumentationTypeMode.OAS_30;
  80. private String basePackage = "com.example.demo.db.controller";
  81. private SwaggerApiInfo apiInfo = new SwaggerApiInfo();
  82. public DocumentationTypeMode getDocumentationType() {
  83. return documentationType;
  84. }
  85. public void setDocumentationType(DocumentationTypeMode documentationType) {
  86. this.documentationType = documentationType;
  87. }
  88. public String getBasePackage() {
  89. return basePackage;
  90. }
  91. public void setBasePackage(String basePackage) {
  92. this.basePackage = basePackage;
  93. }
  94. public SwaggerApiInfo getApiInfo() {
  95. return apiInfo;
  96. }
  97. public void setApiInfo(SwaggerApiInfo apiInfo) {
  98. this.apiInfo = apiInfo;
  99. }
  100. }
  101. //文档信息联系人实体类
  102. public static class SwaggerApiInfoContact {
  103. private String name;
  104. private String url;
  105. private String email;
  106. public String getName() {
  107. return name;
  108. }
  109. public void setName(String name) {
  110. this.name = name;
  111. }
  112. public String getUrl() {
  113. return url;
  114. }
  115. public void setUrl(String url) {
  116. this.url = url;
  117. }
  118. public String getEmail() {
  119. return email;
  120. }
  121. public void setEmail(String email) {
  122. this.email = email;
  123. }
  124. }
  125. //文档信息联系人实体类
  126. public static class SwaggerApiInfo {
  127. private String title;
  128. private String description;
  129. @NestedConfigurationProperty
  130. private SwaggerApiInfoContact contact;
  131. public String getTitle() {
  132. return title;
  133. }
  134. public void setTitle(String title) {
  135. this.title = title;
  136. }
  137. public String getDescription() {
  138. return description;
  139. }
  140. public void setDescription(String description) {
  141. this.description = description;
  142. }
  143. public SwaggerApiInfoContact getContact() {
  144. return contact;
  145. }
  146. public void setContact(SwaggerApiInfoContact contact) {
  147. this.contact = contact;
  148. }
  149. }
  150. //生产通过接口入参
  151. private List<RequestParameter> getGlobalRequestParameters() {
  152. List<RequestParameter> parameters = new ArrayList<>();
  153. parameters.add(new RequestParameterBuilder()
  154. .name("appid")
  155. .description("平台id")
  156. .required(true)
  157. .in(ParameterType.QUERY)
  158. .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
  159. .required(false)
  160. .build());
  161. parameters.add(new RequestParameterBuilder()
  162. .name("udid")
  163. .description("设备的唯一id")
  164. .required(true)
  165. .in(ParameterType.QUERY)
  166. .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
  167. .required(false)
  168. .build());
  169. parameters.add(new RequestParameterBuilder()
  170. .name("version")
  171. .description("客户端的版本号")
  172. .required(true)
  173. .in(ParameterType.QUERY)
  174. .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
  175. .required(false)
  176. .build());
  177. return parameters;
  178. }
  179. //生成通用响应信息
  180. private List<Response> getGlobalResonseMessage() {
  181. List<Response> responseList = new ArrayList<>();
  182. responseList.add(new ResponseBuilder()
  183. .code("404")
  184. .description("找不到资源")
  185. .build());
  186. responseList.add(new ResponseBuilder()
  187. .code("0")
  188. .description("成功")
  189. .build());
  190. responseList.add(new ResponseBuilder()
  191. .code("10")
  192. .description("系统异常")
  193. .build());
  194. responseList.add(new ResponseBuilder()
  195. .code("20")
  196. .description("参数错误")
  197. .build());
  198. responseList.add(new ResponseBuilder()
  199. .code("30")
  200. .description("系统异常")
  201. .build());
  202. //或者通过枚举类添加
  203. // for (ResponseStatusEnum value:ResponseStatusEnum.values()) {
  204. // String code = String.valueOf(value.getCode());
  205. // String message =value.getMessage();
  206. // responseList.add(new ResponseBuilder().code(code).description(message);
  207. // }
  208. return responseList;
  209. }
  210. }

4、编写Ctronller类

  1. package com.example.demo.db.controller;
  2. import com.example.demo.db.domain.Student;
  3. import io.swagger.annotations.*;
  4. import org.springframework.web.bind.annotation.*;
  5. @Api(tags = "学生信息Controller")
  6. @RestController
  7. @RequestMapping(value = "/Student",method = RequestMethod.GET)
  8. public class StudentController{
  9. @ApiOperation(value ="学生信息查询findAllStudent接口",notes = "注意点说明:接口通过id获取用户的详细信息,id必须传递")
  10. @ApiImplicitParams({
  11. @ApiImplicitParam(name = "sid", value = "用户id", required = true, dataType = "String", paramType = "query",defaultValue = "01"),
  12. @ApiImplicitParam(name = "sname", value = "用户姓名", required = false, dataType = "String", paramType = "query",defaultValue = "赵雷"),
  13. })
  14. @RequestMapping(value = "/findAllStudent")
  15. public Student findAllStudent(String sid,String sname){
  16. return null;
  17. }
  18. }

5、启动访问地址:

http://localhost:8011/doc.html (加入UI优化依赖的访问路径)

http://localhost:8011/swagger-ui/index.html (原始路径)

6、Swagger3常用注解说明

@Api:用在请求的类上,说明该类的作用

参数:
tags:说明这个类的作用
value:这个参数没有什么意义,不需要配置

  1. @Api(tags = "学生信息Controller")

@ApiOperation:用在请求的方法上,说明方法的作用

  1. 参数:
  2. value:说明方法的作用
  3. notes:方法的备注说明
  1. @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:用在方法参数里,指定对应请求参数的配置信息

  1. @ApiImplicitParams({
  2. @ApiImplicitParam(name = "sid", value = "用户id", required = true, dataType = "String", paramType = "query",defaultValue = "01"),
  3. @ApiImplicitParam(name = "sname", value = "用户姓名", required = false, dataType = "String", paramType = "query",defaultValue = "赵雷"),
  4. })
  1. findAllStudent(@ApiParam(value = "id",name="id",required = true,defaultValue = "01") String id){

@ApiModel和@ApiModelProperty

(1)@ApiModel:用于响应类上,表示一个返回响应数据的信息
(这种一般用在post创建的时候,使用@RequestBody这样的场景,
请求参数无法使用@ApiImplicitParam注解进行描述的时候)
(2)@ApiModelProperty:用在属性上,描述响应类的属性

  1. @ApiModel(value = "Student实体类",description = "学生实体对象")
  2. @Data
  3. public class Student implements Serializable {
  4. @ApiModelProperty("学生id")
  5. private String sid;
  6. @ApiModelProperty("学生姓名")
  7. private String sname;
  8. @ApiModelProperty("学生年龄")
  9. private Date sage;
  10. @ApiModelProperty("学生性别")
  11. private String ssex;
  12. }

@ApiResponses和@ApiResponse

(1)@ApiResponses:用于请求的方法上,表示一组响应
(2)@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类

  1. @ApiResponses({
  2. @ApiResponse(code=400,message="请求参数没填好"),
  3. @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
  4. })
标签: spring boot java spring

本文转载自: https://blog.csdn.net/zhanhjxxx/article/details/122983553
版权归原作者 zhanhjxxx 所有, 如有侵权,请联系我们删除。

“Springboot集成Swagger3详细操作步骤”的评论:

还没有评论