当前位置: 首页 > news >正文

【WEEK14】 【DAY4】Swagger Part 2【English Version】

2024.5.30 Thursday
Following up on 【WEEK14】 【DAY3】Swagger Part 1【English Version】

Contents

  • 16.4. Configure Scanned Interfaces
    • 16.4.1. Modify SwaggerConfig.java
      • 16.4.1.1. Use the .basePackage() Method to Specify the Package Path for Scanning
      • 16.4.1.2. Other Scanning Methods Can Be Found in the Source Code of RequestHandlerSelectors.class
    • 16.4.2. Continue to Modify SwaggerConfig.java
      • 16.4.2.1. Configure Interface Scanning Filters
      • 16.4.2.2. Other Methods:
  • 16.5. Configure Swagger Switch
    • 16.5.1. Modify the Value of enable to Disable Swagger
    • 16.5.2. Dynamically Configure Swagger to Display in Test and Dev Environments, but Not in Prod
      • 16.5.2.1. Modify SwaggerConfig
      • 16.5.2.2. Modify application.properties
      • 16.5.2.3. Create application-dev.properties
      • 16.5.2.4. Create application-pro.properties
      • 16.5.2.5. Restart

16.4. Configure Scanned Interfaces

Configuring scanned interfaces when building Docket using the select() method

16.4.1. Modify SwaggerConfig.java

16.4.1.1. Use the .basePackage() Method to Specify the Package Path for Scanning

package com.P47.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;import java.util.ArrayList;@Configuration  // Equivalent to @Component
@EnableSwagger2 // Enable Swagger2
public class SwaggerConfig {// Configure the bean instance Docket for Swagger, to set specific parameters for Swagger@Beanpublic Docket docket(){return new Docket(DocumentationType.SWAGGER_2)  // See the source code in DocumentationType.class, select the appropriate version for editing.apiInfo(apiInfo()) // Public Docket(DocumentationType documentationType) method, click on ApiInfo to go to ApiInfo.class.select()   // Configure the scanning interface using the .select() method, RequestHandlerSelectors configures how to scan interfaces.apis(RequestHandlerSelectors.basePackage("com.P47.controll")).build();// Click into Docket.class to see the source code of various methods}// Configure Swagger information (apiInfo)private ApiInfo apiInfo(){// Prevent DEFAULT_CONTACT (name changed to contact) from reporting errorsContact contact = new Contact("Contact Name", "Contact URL", "Contact Email");return new ApiInfo("Swagger Api Documentation", // Title"Api Documentation Description", // Description"version 1.0",  // Version number"http://terms.service.url",  // Organization URLcontact,    // Contact information"Apache 2.0",   // License"http://www.apache.org/licenses/LICENSE-2.0",   // License URLnew ArrayList<>() // Extensions);}
}

After restarting, check: only the hello-controller section remains
Insert image description here

16.4.1.2. Other Scanning Methods Can Be Found in the Source Code of RequestHandlerSelectors.class

basePackage(final String basePackage) // Scan interfaces based on package path
any() // Scan all, all interfaces in the project will be scanned
none() // Do not scan interfaceswithMethodAnnotation(final Class<? extends Annotation> annotation)  // Scan based on method annotation, e.g., withMethodAnnotation(GetMapping.class) only scans GET requests
withClassAnnotation(final Class<? extends Annotation> annotation)   // Scan based on class annotation, e.g., withClassAnnotation(Controller.class) only scans interfaces in classes annotated with @Controller

16.4.2. Continue to Modify SwaggerConfig.java

16.4.2.1. Configure Interface Scanning Filters

Add the following filter

.paths(PathSelectors.ant("/P47/**"))    // Click on path to see the initialization of private Predicate<String> pathSelector; Here, using the .ant() method as an example, only scan interfaces with requests starting with /P47

After restarting, check: no methods are displayed
Insert image description here

16.4.2.2. Other Methods:

Insert image description here
Here is the translated content while keeping the non-comment parts of the code unchanged:

At this time, the complete modified code

package com.P47.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;import java.util.ArrayList;@Configuration  // Equivalent to @Component
@EnableSwagger2 // Enable Swagger2
public class SwaggerConfig {// Configure the bean instance Docket for Swagger, to set specific parameters for Swagger@Beanpublic Docket docket(){return new Docket(DocumentationType.SWAGGER_2)  // See the source code in DocumentationType.class, select the appropriate version for editing.apiInfo(apiInfo()) // Public Docket(DocumentationType documentationType) method, click on ApiInfo to go to ApiInfo.class.select()   // Configure the scanning interface using the .select() method, RequestHandlerSelectors configures how to scan interfaces.apis(RequestHandlerSelectors.basePackage("com.P47.controll"))  // Use basePackage to specify the package to scan.paths(PathSelectors.ant("/P47/**"))    // Click on path to see the initialization of private Predicate<String> pathSelector; Here, using the .ant() method as an example, only scan interfaces with requests starting with /P47.build();// Click into Docket.class to see the source code of various methods/*RequestHandlerSelectors. MethodsbasePackage(final String basePackage) // Scan interfaces based on package pathany() // Scan all, all interfaces in the project will be scannednone() // Do not scan interfaceswithMethodAnnotation(final Class<? extends Annotation> annotation)  // Scan based on method annotation, e.g., withMethodAnnotation(GetMapping.class) only scans GET requestswithClassAnnotation(final Class<? extends Annotation> annotation)   // Scan based on class annotation, e.g., withClassAnnotation(Controller.class) only scans interfaces in classes annotated with @Controller*//*PathSelectors. Methodsany() // Scan any requestnone() // Do not scan any requestregex(final String pathRegex) // Control through regular expressionsant(final String antPattern) // Control through ant()*/}// Configure Swagger information (apiInfo)private ApiInfo apiInfo(){// Prevent DEFAULT_CONTACT (name changed to contact) from reporting errorsContact contact = new Contact("Contact Name", "Contact URL", "Contact Email");return new ApiInfo("Swagger Api Documentation", // Title"Api Documentation Description", // Description"version 1.0",  // Version number"http://terms.service.url",  // Organization URLcontact,    // Contact information"Apache 2.0",   // License"http://www.apache.org/licenses/LICENSE-2.0",   // License URLnew ArrayList<>() // Extensions);}
}

16.5. Configure Swagger Switch

Modify SwaggerConfig.java

16.5.1. Modify the Value of enable to Disable Swagger

@Bean
public Docket docket(){return new Docket(DocumentationType.SWAGGER_2)  // See the source code in DocumentationType.class, select the appropriate version for editing.apiInfo(apiInfo()) // Public Docket(DocumentationType documentationType) method, click on ApiInfo to go to ApiInfo.class.enable(false)  // Whether to enable Swagger, if false it cannot be started, and the page shows: 😱 Could not render e, see the console..select()   // Configure the scanning interface using the .select() method, RequestHandlerSelectors configures how to scan interfaces//.apis(RequestHandlerSelectors.basePackage("com.P47.controll"))  // Use basePackage to specify the package to scan//.paths(PathSelectors.ant("/P47/**"))    // Click on path to see the initialization of private Predicate<String> pathSelector; Here, using the .ant() method as an example, only scan interfaces with requests starting with /P47.build();}

Restart:
Insert image description here

16.5.2. Dynamically Configure Swagger to Display in Test and Dev Environments, but Not in Prod

16.5.2.1. Modify SwaggerConfig

@Bean
public Docket docket(Environment environment){// Set the environments where Swagger should be displayedProfiles profiles = Profiles.of("dev", "test");// Determine if the current environment matches the profiles// Use enable() to accept this parameter and decide whether to display Swaggerboolean flag = environment.acceptsProfiles(profiles);return new Docket(DocumentationType.SWAGGER_2)  // See the source code in DocumentationType.class, select the appropriate version for editing.apiInfo(apiInfo()) // Public Docket(DocumentationType documentationType) method, click on ApiInfo to go to ApiInfo.class.enable(flag)  // Whether to enable Swagger, if false it cannot be started, and the page shows: 😱 Could not render e, see the console..select()   // Configure the scanning interface using the .select() method, RequestHandlerSelectors configures how to scan interfaces//.apis(RequestHandlerSelectors.basePackage("com.P47.controll"))  // Use basePackage to specify the package to scan//.paths(PathSelectors.ant("/P47/**"))    // Click on path to see the initialization of private Predicate<String> pathSelector; Here, using the .ant() method as an example, only scan interfaces with requests starting with /P47.build();}

At this time, the complete code:

package com.P47.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;import java.util.ArrayList;@Configuration  // Equivalent to @Component
@EnableSwagger2 // Enable Swagger2
public class SwaggerConfig {// Configure the bean instance Docket for Swagger, to set specific parameters for Swagger@Beanpublic Docket docket(Environment environment){// Set the environments where Swagger should be displayedProfiles profiles = Profiles.of("dev", "test");// Determine if the current environment matches the profiles// Use enable() to accept this parameter and decide whether to display Swaggerboolean flag = environment.acceptsProfiles(profiles);return new Docket(DocumentationType.SWAGGER_2)  // See the source code in DocumentationType.class, select the appropriate version for editing.apiInfo(apiInfo()) // Public Docket(DocumentationType documentationType) method, click on ApiInfo to go to ApiInfo.class.enable(flag)  // Whether to enable Swagger, if false it cannot be started, and the page shows: 😱 Could not render e, see the console..select()   // Configure the scanning interface using the .select() method, RequestHandlerSelectors configures how to scan interfaces//.apis(RequestHandlerSelectors.basePackage("com.P47.controll"))  // Use basePackage to specify the package to scan//.paths(PathSelectors.ant("/P47/**"))    // Click on path to see the initialization of private Predicate<String> pathSelector; Here, using the .ant() method as an example, only scan interfaces with requests starting with /P47.build();}// Configure Swagger information (apiInfo)private ApiInfo apiInfo(){// Prevent DEFAULT_CONTACT (name changed to contact) from reporting errorsContact contact = new Contact("Contact Name", "Contact URL", "Contact Email");return new ApiInfo("Swagger Api Documentation", // Title"Api Documentation Description", // Description"version 1.0",  // Version number"http://terms.service.url",  // Organization URLcontact,    // Contact information"Apache 2.0",   // License"http://www.apache.org/licenses/LICENSE-2.0",   // License URLnew ArrayList<>() // Extensions);}
}

16.5.2.2. Modify application.properties

spring.application.name=swagger-demo
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
spring.profiles.active=dev

16.5.2.3. Create application-dev.properties

# Production environment
server.port=8081

16.5.2.4. Create application-pro.properties

# Test environment
server.port=8082

16.5.2.5. Restart

Access http://localhost:8081/swagger-ui.html
Insert image description here
Change the configuration in application.properties to spring.profiles.active=pro, and access http://localhost:8082/swagger-ui.html to find that the Swagger page cannot be accessed.
Insert image description here
Similarly, if you do not specify a profile in spring.profiles.active, the default port is 8080. Due to the configuration in SwaggerConfig, http://localhost:8080/swagger-ui.html cannot access Swagger either.
Insert image description here

相关文章:

  • ubuntu18.04 报错:fatal error: execution
  • 浏览器修改后端返回值
  • NKCTF 2024 webshell_pro
  • CI/CD:持续集成/持续部署
  • java web爬虫
  • 【OpenHarmony】TypeScript 语法 ③ ( 条件语句 | if else 语句 | switch case 语句 )
  • [数据集][目标检测]老鼠检测数据集VOC+YOLO格式4107张1类别
  • 反激电源压敏电阻设计
  • Python Config 用法:探索配置文件的艺术
  • 基于 IP 的 DDOS 攻击实验
  • 3.基础光照
  • 进程间通信(27000字超详解)
  • 领域建模(系统操作复习)
  • Prime1 - 提权的另一种解法,彻底搞懂OpenSSL解密渗透提权,超强思路版。
  • leetcode155. 最小栈
  • 时间复杂度分析经典问题——最大子序列和
  • 【comparator, comparable】小总结
  • 【vuex入门系列02】mutation接收单个参数和多个参数
  • 4月23日世界读书日 网络营销论坛推荐《正在爆发的营销革命》
  • C++回声服务器_9-epoll边缘触发模式版本服务器
  • CSS进阶篇--用CSS开启硬件加速来提高网站性能
  • javascript 总结(常用工具类的封装)
  • Java应用性能调优
  • Magento 1.x 中文订单打印乱码
  • Python_网络编程
  • Spring Security中异常上抛机制及对于转型处理的一些感悟
  • 从0到1:PostCSS 插件开发最佳实践
  • 从零开始学习部署
  • 构造函数(constructor)与原型链(prototype)关系
  • 机器人定位导航技术 激光SLAM与视觉SLAM谁更胜一筹?
  • 以太坊客户端Geth命令参数详解
  • 自动记录MySQL慢查询快照脚本
  • 关于Kubernetes Dashboard漏洞CVE-2018-18264的修复公告
  • ​一、什么是射频识别?二、射频识别系统组成及工作原理三、射频识别系统分类四、RFID与物联网​
  • #define MODIFY_REG(REG, CLEARMASK, SETMASK)
  • #我与Java虚拟机的故事#连载19:等我技术变强了,我会去看你的 ​
  • #职场发展#其他
  • (2024,Flag-DiT,文本引导的多模态生成,SR,统一的标记化,RoPE、RMSNorm 和流匹配)Lumina-T2X
  • (delphi11最新学习资料) Object Pascal 学习笔记---第5章第5节(delphi中的指针)
  • (done) ROC曲线 和 AUC值 分别是什么?
  • (二十三)Flask之高频面试点
  • * CIL library *(* CIL module *) : error LNK2005: _DllMain@12 already defined in mfcs120u.lib(dllmodu
  • ./include/caffe/util/cudnn.hpp: In function ‘const char* cudnnGetErrorString(cudnnStatus_t)’: ./incl
  • .NET Framework 和 .NET Core 在默认情况下垃圾回收(GC)机制的不同(局部变量部分)
  • .NET/C# 检测电脑上安装的 .NET Framework 的版本
  • .NETCORE 开发登录接口MFA谷歌多因子身份验证
  • .vimrc 配置项
  • ??在JSP中,java和JavaScript如何交互?
  • @DataRedisTest测试redis从未如此丝滑
  • @NestedConfigurationProperty 注解用法
  • []error LNK2001: unresolved external symbol _m
  • [<死锁专题>]
  • [20160902]rm -rf的惨案.txt
  • [Android] 240204批量生成联系人,短信,通话记录的APK
  • [Angular 基础] - 表单:响应式表单