如何实现 EnvironmentPostProcessor 加载 @ConfigurationProperties 类以进行 Spring boot 测试?

问题描述 投票:0回答:0

我正在为 spring boot 2.7.6 应用程序编写测试,并且有一个 TestResourceLoader 类用于从实现 EnvironmentPostProcessor 接口的测试/资源加载 yml 属性(application-test.yml)文件,如下所示:

public class TestResourceLoader implements EnvironmentPostProcessor {
private static final String TEST_YAML_FILE = "application-test.yml";


@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    try {
        Resource resource = new ClassPathResource(TEST_YAML_FILE);
        if (resource.exists()) {
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);
            MutablePropertySources propertySources = environment.getPropertySources();
            PropertiesPropertySource propertySource = new PropertiesPropertySource(TEST_YAML_FILE, properties);
            propertySources.addLast(propertySource);

            Binder binder = Binder.get(environment);
            binder.bind("database", Bindable.ofInstance(new DatabaseConfiguration()));
        }
    } catch (IOException e) {
        // Handle exception if the YAML file cannot be loaded
    }
    }
}

然而,尽管在 TestResourceLoader 中有完整的类路径,但它似乎没有工作

资源/META-INF/spring.factories

作为

org.springframework.boot.env.EnvironmentPostProcessor=
com.abc.app.testutils.TestResourceLoader

请帮我解决以 yml 格式加载我的配置属性文件的问题。

java spring-boot gradle java-11 spring-boot-test
© www.soinside.com 2019 - 2024. All rights reserved.