spring bean 循环依赖问题,在本地环境可以,测试环境报循环依赖问题

spring 在某些情况下是存在这样的问题:
https://github.com/spring-projects/spring-framework/issues/18879
https://github.com/spring-projects/spring-framework/issues/24325
https://stackoverflow.com/questions/29347723/why-does-spring-get-circular-dependency-issues-on-one-machine-and-not-another

 

解决办法:
1. 去循环依赖
2. @Lazy
3. InitializingBean 时,从 context 中获取
4. @PostConstruct 去设置 bean 依赖
https://www.baeldung.com/circular-dependencies-in-spring

 

为什么在本地可以,上了测试环境就不行,或者上了生产环境就不行了?  

答:根源在于在不同的操作系统或者环境下, bean 的加载顺序是不固定的。bean 加载顺序变化之后,就可能会导致循环依赖报错问题产生!因为,顺序变化之后,循环依赖的主体变了!
bean 加载时,会先将所有的 BeanDefinition 扫描出来,扫描出来的顺序基本上就决定了 bean 的加载顺序。
扫描 BeanDefiniton 的方法是 ClassPathScanningCandidateComponentProvider#scanCandidateComponents(),这个方法在不同的环境下扫描出类的顺序是不固定的。
它的底层走的是 java.lang.ClassLoader#getResources() ,这个方法没有承诺获取到资源文件的顺序

 1 // PathMatchingResourcePatternResolver#doFindAllClassPathResources
 2 protected Set<Resource> doFindAllClassPathResources(String path) throws IOException {
 3     Set<Resource> result = new LinkedHashSet<>(16);
 4     ClassLoader cl = getClassLoader();
 5     Enumeration<URL> resourceUrls = (cl != null ? cl.getResources(path) : ClassLoader.getSystemResources(path));
 6     while (resourceUrls.hasMoreElements()) {
 7         URL url = resourceUrls.nextElement();
 8         result.add(convertClassLoaderURL(url));
 9     }
10     if (!StringUtils.hasLength(path)) {
11         // The above result is likely to be incomplete, i.e. only containing file system references.
12         // We need to have pointers to each of the jar files on the classpath as well...
13         addAllClassLoaderJarRoots(cl, result);
14     }
15     return result;
16 }

 

如果不清楚循环依赖的主体是什么意思,可以参考博主的另外一篇文章:https://blog.csdn.net/wang489687009/article/details/122284171#_61 

 

posted on 2021-05-13 14:54  快鸟  阅读(3143)  评论(0编辑  收藏  举报