最近想體驗下最新版本的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后綴了。
循環依賴
啟動項目后,由于SpringBoot禁止了循環引用,我們會遇到第一個問題,securityConfig和umsAdminServiceImpl循環引用了,具體日志如下;
具體來說就是我們的SecurityConfig引用了UmsAdminService;
而UmsAdminServiceImpl又引用了PasswordEncoder;
由于SecurityConfig繼承了
WebSecurityConfigurerAdapter,而Adapter又引用了PasswordEncoder,這樣就導致了循環引用。
要解決這個問題其實很簡單,你可以修改application.yml直接允許循環引用,不過這個方法有點粗暴,在沒有其他方法的時候可以使用;
其實循環引用主要是因為會導致Spring不知道該先創建哪個Bean才會被禁用的,我們可以使用@Lazy注解指定某個Bean進行懶加載就可以優雅解決該問題,比如在SecurityConfig中懶加載UmsAdminService。
啟動出錯
再次啟動SpringBoot應用后會出現一個空指針異常,一看就是Swagger問題,原來挺好用的Swagger不能用了!
在Swagger的配置類中添加如下Bean可以解決該問題;
/** * Swagger2API文檔的配置 */@ConfigurationpublicclassSwagger2Config{@BeanpublicstaticBeanPostProcessorspringfoxHandlerProviderBeanPostProcessor(){returnnewBeanPostProcessor() {@OverridepublicObjectpostProcessAfterInitialization(Object bean, String beanName)throwsBeansException{if(beaninstanceofWebMvcRequestHandlerProvider || beaninstanceofWebFluxRequestHandlerProvider) {? ? ? ? ? ? ? ? ? ? customizeSpringfoxHandlerMappings(getHandlerMappings(bean));? ? ? ? ? ? ? ? }returnbean;? ? ? ? ? ? }privatevoidcustomizeSpringfoxHandlerMappings(List<T> mappings){? ? ? ? ? ? ? ? List copy = mappings.stream()? ? ? ? ? ? ? ? ? ? ? ? .filter(mapping -> mapping.getPatternParser() ==null)? ? ? ? ? ? ? ? ? ? ? ? .collect(Collectors.toList());? ? ? ? ? ? ? ? mappings.clear();? ? ? ? ? ? ? ? mappings.addAll(copy);? ? ? ? ? ? }@SuppressWarnings("unchecked")privateListgetHandlerMappings(Object bean){try{? ? ? ? ? ? ? ? ? ? Field field = ReflectionUtils.findField(bean.getClass(),"handlerMappings");? ? ? ? ? ? ? ? ? ? field.setAccessible(true);return(List) field.get(bean);? ? ? ? ? ? ? ? }catch(IllegalArgumentException | IllegalAccessException e) {thrownewIllegalStateException(e);? ? ? ? ? ? ? ? }? ? ? ? ? ? }? ? ? ? };? ? }}
文檔無法顯示
再次啟動后訪問Swagger文檔,會發現之前好好的文檔也無法顯示了,訪問地址:http://localhost:8088/swagger-ui/
修改application.yml文件,MVC默認的路徑匹配策略為PATH_PATTERN_PARSER,需要修改為ANT_PATH_MATCHER;
再次啟動后發現Swagger已經可以正常使用了!
聊聊springfox
提到Swagger,我們一般在SpringBoot中集成的都是springfox給我們提供的工具庫,看了下官網,該項目已經快兩年沒有發布新版本了。
再看下Maven倉庫中的版本,依舊停留在之前的3.0.0版本。如果springfox再不出新版本的話,估計隨著SpringBoot版本的更新,兼容性會越來越差的!
總結
今天帶大家體驗了一把SpringBoot升級2.6.x版本的過程,主要解決了循環依賴和Swagger無法使用的問題,希望對大家有所幫助!