Spring boot 3.x版本和swagger 2.0整合问题

swagger 2.0版本和spring boo 3.x版本整合暂时是不行的,因为swagger的依赖底层用的是javax依赖包,而spring boot 3.x版本都是jakarta依赖包,一般是把spring boot2.5以下就可以了,但是想要2.5版本以上spring boot启动就会出报错

Failed to start bean 'documentationPluginsBootstrapper'

解决方法:需要一个配置

spring boot依赖


        org.springframework.boot
        spring-boot-starter-parent
        2.7.9
         

swagger依赖:一个启动器,里面包含了swaggerUi和swagger其他的核心


            io.springfox
            springfox-boot-starter
            3.0.0

核心配置:SwaggerConfig照抄就行 

@Configuration
public class SwaggerConfig {
    @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  void customizeSpringfoxHandlerMappings(List mappings) {
                List copy = mappings.stream()
                        .filter(mapping -> mapping.getPatternParser() == null)
                        .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

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

}

访问swagger页面:我的是8080端口所以就是http://localhost:8080/swagger-ui/index.html,注意想要swagger的注解生效需要加上 @EnableSwagger2 注解

@SpringBootApplication
@EnableSwagger2
public class Demo08SwaggerApplication {
    public static void main(String[] args) {
        SpringApplication.run(Demo08SwaggerApplication.class, args);
    }

}

swagger-ui默认开启,可以在配置文件关闭

springfox:
  documentation:
    swagger-ui:
      enabled: false

如果页面不显示你的接口信息也就是自定义的controller需要在启动类加上@EnableWebMvc注解

你可能感兴趣的:(spring,boot,java,spring)