【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. Configure Scanned Interfaces)
    • [16.4.1. Modify SwaggerConfig.java](#16.4.1. Modify SwaggerConfig.java)
      • [16.4.1.1. Use the .basePackage() Method to Specify the Package Path for Scanning](#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.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. Continue to Modify SwaggerConfig.java)
      • [16.4.2.1. Configure Interface Scanning Filters](#16.4.2.1. Configure Interface Scanning Filters)
      • [16.4.2.2. Other Methods:](#16.4.2.2. Other Methods:)
  • [16.5. Configure Swagger Switch](#16.5. Configure Swagger Switch)
    • [16.5.1. Modify the Value of enable to Disable Swagger](#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. Dynamically Configure Swagger to Display in Test and Dev Environments, but Not in Prod)
      • [16.5.2.1. Modify SwaggerConfig](#16.5.2.1. Modify SwaggerConfig)
      • [16.5.2.2. Modify application.properties](#16.5.2.2. Modify application.properties)
      • [16.5.2.3. Create application-dev.properties](#16.5.2.3. Create application-dev.properties)
      • [16.5.2.4. Create application-pro.properties](#16.5.2.4. Create application-pro.properties)
      • [16.5.2.5. Restart](#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

java 复制代码
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
    @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
                .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 errors
        Contact 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 URL
                contact,    // Contact information
                "Apache 2.0",   // License
                "http://www.apache.org/licenses/LICENSE-2.0",   // License URL
                new ArrayList<>() // Extensions
        );
    }
}

After restarting, check: only the hello-controller section remains

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

java 复制代码
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 interfaces

withMethodAnnotation(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

java 复制代码
.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

16.4.2.2. Other Methods:

Here is the translated content while keeping the non-comment parts of the code unchanged:

At this time, the complete modified code

java 复制代码
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
    @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
                .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. Methods
        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 interfaces

        withMethodAnnotation(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
        */

        /*PathSelectors. Methods
        any() // Scan any request
        none() // Do not scan any request
        regex(final String pathRegex) // Control through regular expressions
        ant(final String antPattern) // Control through ant()
        */
    }

    // Configure Swagger information (apiInfo)
    private ApiInfo apiInfo(){

        // Prevent DEFAULT_CONTACT (name changed to contact) from reporting errors
        Contact 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 URL
                contact,    // Contact information
                "Apache 2.0",   // License
                "http://www.apache.org/licenses/LICENSE-2.0",   // License URL
                new ArrayList<>() // Extensions
        );
    }
}

16.5. Configure Swagger Switch

Modify SwaggerConfig.java

16.5.1. Modify the Value of enable to Disable Swagger

java 复制代码
@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:

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

16.5.2.1. Modify SwaggerConfig

java 复制代码
@Bean
public Docket docket(Environment environment){

    // Set the environments where Swagger should be displayed
    Profiles profiles = Profiles.of("dev", "test");
    // Determine if the current environment matches the profiles
    // Use enable() to accept this parameter and decide whether to display Swagger
    boolean 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:

java 复制代码
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
    @Bean
    public Docket docket(Environment environment){

        // Set the environments where Swagger should be displayed
        Profiles profiles = Profiles.of("dev", "test");
        // Determine if the current environment matches the profiles
        // Use enable() to accept this parameter and decide whether to display Swagger
        boolean 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 errors
        Contact 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 URL
                contact,    // Contact information
                "Apache 2.0",   // License
                "http://www.apache.org/licenses/LICENSE-2.0",   // License URL
                new ArrayList<>() // Extensions
        );
    }
}

16.5.2.2. Modify application.properties

xml 复制代码
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

xml 复制代码
# Production environment
server.port=8081

16.5.2.4. Create application-pro.properties

xml 复制代码
# Test environment
server.port=8082

16.5.2.5. Restart

Access http://localhost:8081/swagger-ui.html

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.

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.

相关推荐
老K的Java兵器库7 分钟前
并发集合踩坑现场:ConcurrentHashMap size() 阻塞、HashSet 并发 add 丢数据、Queue 伪共享
java·后端·spring
冷冷的菜哥25 分钟前
go邮件发送——附件与图片显示
开发语言·后端·golang·邮件发送·smtp发送邮件
向葭奔赴♡26 分钟前
Spring Boot 分模块:从数据库到前端接口
数据库·spring boot·后端
计算机毕业设计木哥28 分钟前
计算机毕业设计选题推荐:基于SpringBoot和Vue的爱心公益网站
java·开发语言·vue.js·spring boot·后端·课程设计
ANnianStriver30 分钟前
智谱大模型实现文生视频案例
java·aigc
普通网友40 分钟前
KUD#73019
java·php·程序优化
IT_陈寒43 分钟前
Redis 性能翻倍的 5 个隐藏技巧,99% 的开发者都不知道第3点!
前端·人工智能·后端
JaguarJack44 分钟前
PHP 桌面端框架NativePHP for Desktop v2 发布!
后端·php·laravel
番茄Salad1 小时前
自定义Spring Boot Starter项目并且在其他项目中通过pom引入使用
java·spring boot
程序员三明治1 小时前
详解Redis锁误删、原子性难题及Redisson加锁底层原理、WatchDog续约机制
java·数据库·redis·分布式锁·redisson·watchdog·看门狗