springboot2.7.6 集成swagger

发布于:2024-07-07 ⋅ 阅读:(167) ⋅ 点赞:(0)

在 Spring Boot 2.7.6 版本中集成 Swagger 的步骤相对直接,主要涉及添加依赖、编写配置以及在控制器中添加文档注解几个环节。

下面是集成 Swagger 的基本步骤:

1. 添加依赖

        首先,在pom.xml文件中添加 Swagger 相关依赖。

        对于 Spring Boot 2.x 版本,推荐使用 springfox-boot-starter,这是一个包含 Swagger UI 和 Swagger 2 功能的启动器模块。

<dependencies>
    <!-- Springfox Swagger UI and Swagger 2 support -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version> <!-- 确认最新的版本号 -->
    </dependency>
    <!-- 其他依赖... -->
</dependencies>

2. 编写 Swagger 配置

        创建一个配置类来设置 Swagger 的基本信息,比如 API 文档的基本信息、扫描的包路径等。

#swgger启用标识  true启用 false不启用
sys:
  swagger:
    enable-swgger: true
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

@Configuration
@EnableSwagger2WebMvc // 如果使用的是Springfox 3.x,则启用此注解
public class SwaggerConfig {

    @Value("${sys.swagger.enable-swgger}")
	private Boolean enableSwgger;

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(enableSwgger)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Your API Title")
                .description("Description of your API")
                .version("1.0.0")
                .build();
    }
}

3. 在控制器中使用注解

        在REST 控制器类和方法上添加 Swagger 提供的注解,以便生成详细的文档信息。

        @Api: 用于类级别,描述控制器的作用。

        @ApiOperation: 用于方法级别,描述具体操作。

        @ApiParam: 用于方法参数,描述参数详情。

        @ApiResponse: 用于方法,描述响应详情。

        @ApiModel 和 @ApiModelProperty: 用于模型对象,描述返回实体的属性。

        例如:

@RestController
@RequestMapping("/api/users")
@Api(value = "User Management", description = "User CRUD operations")
public class UserController {

    @GetMapping("/{id}")
    @ApiOperation(value = "Find user by ID", notes = "Returns a single user")
    @ApiResponses({
            @ApiResponse(code = 200, message = "Successfully retrieved user"),
            @ApiResponse(code = 404, message = "User not found")
    })
    public ResponseEntity<User> getUser(@PathVariable Long id) {
        // ... implementation
    }
    // ... other methods
}

4. 访问 Swagger UI

        配置完成后,启动 Spring Boot 应用,然后访问 http://localhost:8080/doc.html(默认端口为8080,根据实际情况调整),应该能看到 Swagger UI 页面,其中列出了所有被扫描到的 API 接口及其详细信息。

5、问题记录

        5.1、启动报错

        报错信息如下:

org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
	at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.24.jar:5.3.24]
	at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.24.jar:5.3.24]
	at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.24.jar:5.3.24]
	at java.lang.Iterable.forEach(Iterable.java:75) ~[na:1.8.0_77]
	at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) ~[spring-context-5.3.24.jar:5.3.24]
	at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.3.24.jar:5.3.24]
	at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) ~[spring-context-5.3.24.jar:5.3.24]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) ~[spring-context-5.3.24.jar:5.3.24]
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.6.jar:2.7.6]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:731) [spring-boot-2.7.6.jar:2.7.6]
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) [spring-boot-2.7.6.jar:2.7.6]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-2.7.6.jar:2.7.6]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) [spring-boot-2.7.6.jar:2.7.6]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) [spring-boot-2.7.6.jar:2.7.6]
	at com.zklcsoftware.FlowableUiApplication.main(FlowableUiApplication.java:15) [classes/:na]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_77]
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_77]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_77]
	at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_77]
	at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.7.6.jar:2.7.6]

        解决办法:

        需要加上如下配置:

package com.zklcsoftware;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;

import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class BeanPostProcessorConfig {

    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {

            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
                List<T> copy = mappings.stream()
                        .filter(mapping -> mapping.getPatternParser() == null)
                        .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }
}

        5.2、启动成功后,访问swagger-ui页面出现不显示接口信息的问题

        解决办法:

                在application.yml配置文件中加上下面的配置

spring:
  mvc:
    pathmatch:
      matching-strategy: ANT_PATH_MATCHER


网站公告

今日签到

点亮在社区的每一天
去签到