使用swagger时出现Unable to infer base url. This is common when using dynamic servlet registra

该博客介绍了SpringBoot项目中Swagger2的正确配置方法。当仅使用@EnableSwagger2无法识别Controller时,需要创建Swagger配置类,并指定扫描的Controller包路径。通过Docket Bean定制Swagger配置,包括指定API信息和选择要包含的处理程序。配置完成后,可以正常访问Swagger UI页面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
出现以上错误提示的原因是没有启用swagger2,也就是没有使用@EnableSwagger2,很多文章中说在启动类加上@EnableSwagger2即可,虽然添加后能够正常访问http://localhost:8080/swagger-ui.html页面,但是并不能识别到添加swagger相关注解的controller,正确的使用方式是,添加swagger配置类并指定扫描路径:

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author bab
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig{
    @Bean
    public Docket customDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller")) // 指定路径
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("没有说明")
                .version("1.0.0")
                .build();
    }
}

添加以上配置类并重新启动项目即可正常访问http://localhost:8080/swagger-ui.html了。

注意:如果配置类所属的包不是启动类的同级或子级则需要在启动累上自己指定需要扫描对应路径,例如:@ComponentScan("com.example.demo.config")

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值