最近想体验下最新版本的SpringBoot,逛了下官网,发现SpringBoot目前最新版本已经是 2.6.4
了,版本更新确实够快的。之前的项目升级了 2.6.4
版本后发现有好多坑,不仅有循环依赖的问题,连Swagger都没法用了!今天给大家分享下升级过程,填一填这些坑!
聊聊SpringBoot版本
首先我们来聊聊SpringBoot的版本,目前最新版本是 2.6.4
版本, 2.7.x
即将发布, 2.4.x
及以下版本已经停止维护了,目前的主流版本应该是 2.5.x
和 2.6.x
。具体可以看下下面这张表。
升级过程
下面我们将之前的 mall-tiny-swagger
项目升级下,看看到底有哪些坑,这些坑该如何解决!
添加依赖
首先在 pom.xml
中修改SpringBoot的版本号,注意从 2.4.x
版本开始,SpringBoot就不再使用 .RELEASE
后缀了。
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.4</version> <relativePath/> <!-- lookup parent from repository --> </parent>
循环依赖
-
循环引用 securityConfig umsAdminServiceImpl
-
具体来说就是我们的
SecurityConfig
引用了UmsAdminService
;
-
而
UmsAdminServiceImpl
又引用了PasswordEncoder
;
-
SecurityConfig WebSecurityConfigurerAdapter PasswordEncoder
-
要解决这个问题其实很简单,你可以修改
application.yml
直接允许循环引用,不过这个方法有点粗暴,在没有其他方法的时候可以使用;
spring: main: allow-circular-references: true
-
@Lazy SecurityConfig UmsAdminService
启动出错
-
再次启动SpringBoot应用后会出现一个空指针异常,一看就是Swagger问题,原来挺好用的Swagger不能用了!
-
在Swagger的配置类中添加如下Bean可以解决该问题;
/** * Swagger2API文档的配置 */ @Configuration public class Swagger2Config { @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); } } }; } }
文档无法显示
-
再次启动后访问Swagger文档,会发现之前好好的文档也无法显示了,访问地址:http://localhost:8088/swagger-ui/
-
application.yml PATH_PATTERN_PARSER ANT_PATH_MATCHER
spring: mvc: pathmatch: matching-strategy: ANT_PATH_MATCHER
-
再次启动后发现Swagger已经可以正常使用了!
聊聊springfox
提到Swagger,我们一般在SpringBoot中集成的都是springfox给我们提供的工具库,看了下官网,该项目已经快两年没有发布新版本了。
再看下Maven仓库中的版本,依旧停留在之前的 3.0.0
版本。如果springfox再不出新版本的话,估计随着SpringBoot版本的更新,兼容性会越来越差的!
总结
今天带大家体验了一把SpringBoot升级 2.6.x
版本的过程,主要解决了循环依赖和Swagger无法使用的问题,希望对大家有所帮助!