Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

当@SpringBootTest创建多个spring-context时,无法正确获取nacos中配置的属性 #338

Open
vergilyn opened this issue Sep 5, 2024 · 0 comments

Comments

@vergilyn
Copy link

vergilyn commented Sep 5, 2024

spring-boot: 2.7.18
nacos-config-spring-boot-autoconfigure: 0.2.12

问题描述

application.properties 配置示例:

nacos.config.data-id=com.xxx.properties
nacos.config.group=GROUP_XXX
nacos.config.type=properties

当使用 @SpringBootTest 进行单元测试时,存在例如 @SpyBean 或者 @MockBean 时,会多次创建 spring.context(对应多个 spring.environment)。(参考:https://github.com/spring-projects/spring-boot/issues/34768)

但是,只有 第1次创建的 spring.context 中可以获取 com.xxx.properties中配置的属性。
第2+次创建的spring.context 中都无法正确获取com.xxx.properties中的属性。

可能原因

由于 NacosConfigApplicationContextInitializer 中获取的是单例NacosConfigLoader,并且NacosConfigLoader存在对spring.environment的引用。
当多次创建 spring.context 时,NacosConfigLoader引用的始终是第1次创建的spring.environment,导致第2+次无法正确将nacos中的配置项写入spring.environment,从而无法正确创建 spring.context

environment = context.getEnvironment();
nacosConfigProperties = NacosConfigPropertiesUtils
.buildNacosConfigProperties(environment);
final NacosConfigLoader configLoader = NacosConfigLoaderFactory.getSingleton(builder);

public class NacosConfigLoaderFactory {
private static volatile NacosConfigLoader nacosConfigLoader;
public static NacosConfigLoader getSingleton(Function<Properties, ConfigService> builder) {
if (nacosConfigLoader == null) {
synchronized (NacosConfigLoaderFactory.class) {
if (nacosConfigLoader == null) {
nacosConfigLoader = new NacosConfigLoader(builder);
}
}
}
return nacosConfigLoader;
}
}

期望

多次创建spring.context时,能正确将nacos的配置项写入到对应的spring.environment

@vergilyn vergilyn changed the title 由于NacosConfigApplicationContextInitializer中获取的是NacosConfigLoader单例对象,当@SpringBootTest创建多个spring-context无法正确获取nacos中配置的属性 当@SpringBootTest创建多个spring-context时,无法正确获取nacos中配置的属性 Sep 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant