Skip to content

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

@vergilyn

Description

@vergilyn

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions