springboot学习(六十一) 解决springboot2.6和swagger冲突的问题

1、问题

springboot升级到2.6后发现无法启动,和swagger冲突,错误信息如下:

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.13.jar:5.3.13]
	at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.13.jar:5.3.13]
	at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.13.jar:5.3.13]
	at java.lang.Iterable.forEach(Iterable.java:75) ~[?:?]
	at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) ~[spring-context-5.3.13.jar:5.3.13]
	at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.3.13.jar:5.3.13]
	at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) ~[spring-context-5.3.13.jar:5.3.13]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) ~[spring-context-5.3.13.jar:5.3.13]
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.1.jar:2.6.1]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-2.6.1.jar:2.6.1]
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) ~[spring-boot-2.6.1.jar:2.6.1]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.1.jar:2.6.1]
	at com.iscas.biz.BizApp.main(BizApp.java:69) ~[classes/:?]
Caused by: java.lang.NullPointerException
	at springfox.documentation.spring.web.WebMvcPatternsRequestConditionWrapper.getPatterns(WebMvcPatternsRequestConditionWrapper.java:56) ~[springfox-spring-webmvc-3.0.0.jar:3.0.0]
	at springfox.documentation.RequestHandler.sortedPaths(RequestHandler.java:113) ~[springfox-core-3.0.0.jar:3.0.0]
	at springfox.documentation.spi.service.contexts.Orderings.lambda$byPatternsCondition$3(Orderings.java:89) ~[springfox-spi-3.0.0.jar:3.0.0]
	at java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469) ~[?:?]
	at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355) ~[?:?]
	at java.util.TimSort.sort(TimSort.java:234) ~[?:?]
	at java.util.Arrays.sort(Arrays.java:1515) ~[?:?]
	at java.util.ArrayList.sort(ArrayList.java:1750) ~[?:?]
	at java.util.stream.SortedOps$RefSortingSink.end(SortedOps.java:392) ~[?:?]
	at java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[?:?]
	at java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[?:?]
	at java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[?:?]
	at java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[?:?]
	at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485) ~[?:?]
	at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[?:?]
	at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[?:?]
	at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[?:?]
	at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[?:?]
	at springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider.requestHandlers(WebMvcRequestHandlerProvider.java:81) ~[springfox-spring-webmvc-3.0.0.jar:3.0.0]
	at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195) ~[?:?]
	at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655) ~[?:?]
	at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[?:?]
	at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[?:?]
	at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[?:?]
	at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[?:?]
	at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[?:?]
	at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.withDefaults(AbstractDocumentationPluginsBootstrapper.java:107) ~[springfox-spring-web-3.0.0.jar:3.0.0]
	at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.buildContext(AbstractDocumentationPluginsBootstrapper.java:91) ~[springfox-spring-web-3.0.0.jar:3.0.0]
	at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.bootstrapDocumentationPlugins(AbstractDocumentationPluginsBootstrapper.java:82) ~[springfox-spring-web-3.0.0.jar:3.0.0]
	at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.start(DocumentationPluginsBootstrapper.java:100) ~[springfox-spring-web-3.0.0.jar:3.0.0]
	at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178) ~[spring-context-5.3.13.jar:5.3.13]
	... 12 more

目测是因为springboot修改了请求路由匹配策略造成的

8. SpringMVC 默认路径匹配策略
Spring MVC 处理程序映射匹配请求路径的默认策略已从 AntPathMatcher 更改为PathPatternParser。

Actuator端点现在也使用基于 PathPattern 的 URL 匹配。需要注意的是,Actuator端点的路径匹配策略无法通过配置属性进行配置。

如果需要将默认切换回 AntPathMatcher,可以将 spring.mvc.pathmatch.matching-strategy 设置为 ant-path-matcher,比如下面这样:

spring.mvc.pathmatch.matching-strategy=ant-path-matcher

2、解决办法1

找到类:

/*
 *
 *  Copyright 2015-2017 the original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *
 */
package springfox.documentation.spring.web.plugins;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Conditional;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.RequestHandler;
import springfox.documentation.spi.service.RequestHandlerProvider;
import springfox.documentation.spring.web.OnServletBasedWebApplication;
import springfox.documentation.spring.web.WebMvcRequestHandler;
import springfox.documentation.spring.web.readers.operation.HandlerMethodResolver;

import javax.servlet.ServletContext;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import static java.util.stream.Collectors.*;
import static springfox.documentation.builders.BuilderDefaults.*;
import static springfox.documentation.spi.service.contexts.Orderings.*;
import static springfox.documentation.spring.web.paths.Paths.*;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@Conditional(OnServletBasedWebApplication.class)
public class WebMvcRequestHandlerProvider implements RequestHandlerProvider {
    private final List<RequestMappingInfoHandlerMapping> handlerMappings;
    private final HandlerMethodResolver methodResolver;
    private final String contextPath;

//  @Autowired
//  public WebMvcRequestHandlerProvider(
//      Optional<ServletContext> servletContext,
//      HandlerMethodResolver methodResolver,
//      List<RequestMappingInfoHandlerMapping> handlerMappings) {
//    this.handlerMappings = handlerMappings;
//    this.methodResolver = methodResolver;
//    this.contextPath = servletContext
//        .map(ServletContext::getContextPath)
//        .orElse(ROOT);
//  }


    @Autowired
    public WebMvcRequestHandlerProvider(Optional<ServletContext> servletContext, HandlerMethodResolver methodResolver,
                                        List<RequestMappingInfoHandlerMapping> handlerMappings) {
        this.handlerMappings = handlerMappings.stream().filter(mapping -> mapping.getPatternParser() == null)
                .collect(Collectors.toList());
        this.methodResolver = methodResolver;
        this.contextPath = servletContext
                .map(ServletContext::getContextPath)
                .orElse(ROOT);
    }

    @Override
    public List<RequestHandler> requestHandlers() {
        return nullToEmptyList(handlerMappings).stream()
                .filter(requestMappingInfoHandlerMapping ->
                        !("org.springframework.integration.http.inbound.IntegrationRequestMappingHandlerMapping"
                                .equals(requestMappingInfoHandlerMapping.getClass()
                                        .getName())))
                .map(toMappingEntries())
                .flatMap((entries -> StreamSupport.stream(entries.spliterator(), false)))
                .map(toRequestHandler())
                .sorted(byPatternsCondition())
                .collect(toList());
    }

    private Function<RequestMappingInfoHandlerMapping,
            Iterable<Map.Entry<RequestMappingInfo, HandlerMethod>>> toMappingEntries() {
        return input -> input.getHandlerMethods()
                .entrySet();
    }

    private Function<Map.Entry<RequestMappingInfo, HandlerMethod>, RequestHandler> toRequestHandler() {
        return input -> new WebMvcRequestHandler(
                contextPath,
                methodResolver,
                input.getKey(),
                input.getValue());
    }
}

在项目下建一个同名包springfox.documentation.spring.web.plugins
在这里插入图片描述

拷贝上面的类内容,修改其构造器为:

    @Autowired
    public WebMvcRequestHandlerProvider(Optional<ServletContext> servletContext, HandlerMethodResolver methodResolver,
                                        List<RequestMappingInfoHandlerMapping> handlerMappings) {
        this.handlerMappings = handlerMappings.stream().filter(mapping -> Objects.isNull(mapping.getPatternParser())).collect(Collectors.toList());
        this.methodResolver = methodResolver;
        this.contextPath = servletContext
                .map(ServletContext::getContextPath)
                .orElse(ROOT);
    }

修改后完整的类

/*
 *
 *  Copyright 2015-2017 the original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *
 */
package springfox.documentation.spring.web.plugins;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Conditional;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.RequestHandler;
import springfox.documentation.spi.service.RequestHandlerProvider;
import springfox.documentation.spring.web.OnServletBasedWebApplication;
import springfox.documentation.spring.web.WebMvcRequestHandler;
import springfox.documentation.spring.web.readers.operation.HandlerMethodResolver;

import javax.servlet.ServletContext;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import static java.util.stream.Collectors.*;
import static springfox.documentation.builders.BuilderDefaults.*;
import static springfox.documentation.spi.service.contexts.Orderings.*;
import static springfox.documentation.spring.web.paths.Paths.*;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@Conditional(OnServletBasedWebApplication.class)
public class WebMvcRequestHandlerProvider implements RequestHandlerProvider {
    private final List<RequestMappingInfoHandlerMapping> handlerMappings;
    private final HandlerMethodResolver methodResolver;
    private final String contextPath;

//  @Autowired
//  public WebMvcRequestHandlerProvider(
//      Optional<ServletContext> servletContext,
//      HandlerMethodResolver methodResolver,
//      List<RequestMappingInfoHandlerMapping> handlerMappings) {
//    this.handlerMappings = handlerMappings;
//    this.methodResolver = methodResolver;
//    this.contextPath = servletContext
//        .map(ServletContext::getContextPath)
//        .orElse(ROOT);
//  }


    @Autowired
    public WebMvcRequestHandlerProvider(Optional<ServletContext> servletContext, HandlerMethodResolver methodResolver,
                                        List<RequestMappingInfoHandlerMapping> handlerMappings) {
        this.handlerMappings = handlerMappings.stream().filter(mapping -> Objects.isNull(mapping.getPatternParser())).collect(Collectors.toList());
        this.methodResolver = methodResolver;
        this.contextPath = servletContext
                .map(ServletContext::getContextPath)
                .orElse(ROOT);
    }

    @Override
    public List<RequestHandler> requestHandlers() {
        return nullToEmptyList(handlerMappings).stream()
                .filter(requestMappingInfoHandlerMapping ->
                        !("org.springframework.integration.http.inbound.IntegrationRequestMappingHandlerMapping"
                                .equals(requestMappingInfoHandlerMapping.getClass()
                                        .getName())))
                .map(toMappingEntries())
                .flatMap((entries -> StreamSupport.stream(entries.spliterator(), false)))
                .map(toRequestHandler())
                .sorted(byPatternsCondition())
                .collect(toList());
    }

    private Function<RequestMappingInfoHandlerMapping,
            Iterable<Map.Entry<RequestMappingInfo, HandlerMethod>>> toMappingEntries() {
        return input -> input.getHandlerMethods()
                .entrySet();
    }

    private Function<Map.Entry<RequestMappingInfo, HandlerMethod>, RequestHandler> toRequestHandler() {
        return input -> new WebMvcRequestHandler(
                contextPath,
                methodResolver,
                input.getKey(),
                input.getValue());
    }
}

在配置文件内将匹配方式改为ant

spring.mvc.pathmatch.matching-strategy=ant-path-matcher

至此解决了问题,其实是把不符合规则的控制器过滤器掉了。
另外吐槽一下,swagger更新到3.0后一年不更新了,怎么个意思?
有人在评论区吐槽不够优雅,经过试验再更新两种方式

3、解决办法2

添加一个BeanPostProcessor,在postProcessAfterInitialization中修改WebMvcRequestHandlerProvider中的handlerMappings属性,这种方式其实更第一种是一样的,这样不用覆盖原有类,更优雅一些。

package com.iscas.biz.config;

/**
 * 自定义BeanPostProcessor
 *
 * @author zhuquanwen
 * @version 1.0
 * @date 2021/12/29
 * @since jdk11/
 */
@SuppressWarnings({"unused", "unchecked"})
@Component
@Slf4j
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Autowired
    private DefaultListableBeanFactory defaultListableBeanFactory;

    @Override
    public Object postProcessBeforeInitialization(@NotNull Object bean, @NotNull String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(@NotNull Object bean, @NotNull String beanName) throws BeansException {
        handleWebMvcRequestHandlerProvider(beanName, bean);
        return bean;
    }

    private void handleWebMvcRequestHandlerProvider(String beanName, Object bean) {
        // 处理swagger 在spring boot2.6以上不可用的问题
        boolean modify = (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) &&
                defaultListableBeanFactory.containsBean(beanName);
        if (modify) {
            // 修改属性
            try {
                Field handlerMappingsField = bean.getClass().getDeclaredField("handlerMappings");
                ReflectUtils.makeAccessible(handlerMappingsField);
                List<RequestMappingInfoHandlerMapping> handlerMappings = (List<RequestMappingInfoHandlerMapping>) handlerMappingsField.get(bean);
                List<RequestMappingInfoHandlerMapping> tmpHandlerMappings = handlerMappings.stream().filter(mapping -> Objects.isNull(mapping.getPatternParser())).collect(Collectors.toList());
                handlerMappings.clear();
                handlerMappings.addAll(tmpHandlerMappings);
            } catch (Exception e) {
                log.warn("修改WebMvcRequestHandlerProvider的属性:handlerMappings出错,可能导致swagger不可用", e);
            }
        }
    }
}

ReflectUtils.makeAccessible的方法:

    public static void makeAccessible(Field field) {
        if ((!Modifier.isPublic(field.getModifiers()) ||
                !Modifier.isPublic(field.getDeclaringClass().getModifiers()) ||
                Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
            field.setAccessible(true);
        }
    }

4、解决办法3

还有一种办法是注册一个WebMvcEndpointHandlerMapping类

@Bean
    public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier,
                                                                         ServletEndpointsSupplier servletEndpointsSupplier,
                                                                         ControllerEndpointsSupplier controllerEndpointsSupplier,
                                                                         EndpointMediaTypes endpointMediaTypes,
                                                                         CorsEndpointProperties corsProperties,
                                                                         WebEndpointProperties webEndpointProperties,
                                                                         Environment environment) {
        List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>();
        Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
        allEndpoints.addAll(webEndpoints);
        allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
        allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
        String basePath = webEndpointProperties.getBasePath();
        EndpointMapping endpointMapping = new EndpointMapping(basePath);
        boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
        return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(),
                new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping, null);
    }

    private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {

        return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) ||
                ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));

    }

经测试,以上3种方式都可用,大家可自行选择

  • 9
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
### 回答1: Spring Boot 2.6整合Swagger可以通过以下步骤实现: 1. 在pom.xml文件中添加Swagger依赖: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3..</version> </dependency> ``` 2. 在启动类上添加@EnableSwagger2注解: ```java @SpringBootApplication @EnableSwagger2 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 3. 配置Swagger: ```java @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API文档") .description("API文档") .version("1.") .build(); } } ``` 4. 在Controller类上添加Swagger注解: ```java @RestController @Api(tags = "用户管理") @RequestMapping("/user") public class UserController { @ApiOperation(value = "获取用户列表", notes = "获取用户列表") @GetMapping("/list") public List<User> list() { return userService.list(); } @ApiOperation(value = "添加用户", notes = "添加用户") @PostMapping("/add") public void add(@RequestBody User user) { userService.add(user); } } ``` 以上就是Spring Boot 2.6整合Swagger的基本步骤,可以根据实际需求进行配置和调整。 ### 回答2: Spring Boot是一个快速开发的开源框架,其对Spring框架进行了封装,简化了Spring应用的配置和部署。Swagger是一个RESTful风格的API框架,可以帮助我们根据API生成文档、测试API、交互式地调用API等。 在Spring Boot 2.6中,整合Swagger变得更加简单,只需要引入相应的依赖即可开始使用。具体的步骤如下: 1. 引入Swagger依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` 2. 配置Swagger 在程序的启动文件中添加Swagger配置类,如下: ``` @Configuration @EnableSwagger2WebMvc public class SwaggerConfiguration { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("REST API Documentation") .description("Example API Documentation") .version("1.0.0") .build(); } } ``` 在上面的代码中,我们配置了Swagger Documentation的基本信息,并指定了要扫描的包。 3. 启动应用程序 配置完成后,我们可以启动应用程序了。当应用程序成功启动后,我们可以通过访问http://<host>:<port>/swagger-ui/来查看Swagger UI并测试API。 在Swagger UI界面中,我们可以找到每个API端点,并查看其文档和参数。我们可以测试每个API端点并查看其响应。 在整合Swagger过程中,需要注意的是,我们需要保证Swagger和Spring Boot的版本兼容,否则会引起一些异常或错误。同时,在编写API时,我们需要注意编写好文档和注释,以便Swagger可以正确生成API文档。 综上所述,Spring Boot 2.6整合Swagger非常简单,只需几个简单的步骤即可完成。Swagger使得API文档化和API测试变得更加简单,减少了我们的工作量和出错率。 ### 回答3: Spring Boot是一个非常流行的Java Web开发框架,而Swagger是一个API文档工具。通过使用Swagger,我们可以非常方便地为我们的API生成文档。在本篇文章中,我们将详细介绍如何在Spring Boot 2.6中整合Swagger。 一、添加依赖 Swagger是一个开源的项目,我们可以通过Maven或Gradle进行依赖的配置。在这里,我们以Maven为例,添加以下依赖: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` 二、添加Swagger配置 在Spring Boot 2.6中,我们可以使用@EnableSwagger2WebMvc注解来启用Swagger。在配置类上添加该注解即可: ```java @Configuration @EnableSwagger2WebMvc public class SwaggerConfig { } ``` 我们也可以通过SwaggerDocket配置对象来定制Swagger的一些属性,例如API基本信息、扫描包路径等: ```java @Configuration @EnableSwagger2WebMvc public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot Application") .description("This is a sample Spring Boot application using Swagger.") .version("1.0.0") .build(); } } ``` 在这个例子中,我们定义了API的基本信息:标题、描述和版本号。我们还使用了RequestHandlerSelectors.basePackage方法来扫描指定包路径下的Controller类。路径PathSelectors.any表示扫描所有路径。 三、访问Swagger UI 配置完成后,我们就可以通过Swagger UI来查看API文档了。在浏览器中输入http://localhost:8080/swagger-ui.html,就可以进入Swagger UI页面了。 在Swagger UI页面中,我们可以看到应用程序的所有API列表。我们可以单击每个API来查看它的详细信息,例如输入参数、输出参数等等。在右上角的控制台中,我们可以尝试发送HTTP请求,并查看响应结果。 总结 本文介绍了如何在Spring Boot 2.6中整合Swagger。我们添加了Swagger依赖,配置了SwaggerDocket对象,并在浏览器中查看了API文档。Swagger使得我们可以很容易地为我们的API生成文档,从而快速了解和测试API。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值