【问题标题】:Is there a way to get list of loaded properties file in SpringBoot application?有没有办法在 Spring Boot 应用程序中获取加载的属性文件列表?
【发布时间】:2021-06-18 19:35:15
【问题描述】:

当我尝试执行mvn clean install 时,我只在一个平台上遇到了问题。作为构建的一部分,我们编译多个组件,最后我们使用wiremock执行功能测试。它应该从功能测试配置文件中选择特定配置,并且应该从 application.properties 文件中选择默认属性。但由于某种原因,相同的代码无法找到这些文件中提到的属性。所以,只是想知道是否可以通过某种方式获取在 wiremock 期间加载的属性文件列表?这将为为什么没有选择预期的属性文件提供一些线索?

所有属性文件都位于里面:

src/main/resources

并且,从测试类开始。

@ContextConfiguration(classes = SampleFTConfiguration.class)
public class SampleControllerTest{
//test method
}

@ComponentScan("com.xxx.xxx.xxx.ft")
@PropertySource("classpath:application-test.properties")
public class  SampleFTConfiguration{


}

注意:我不希望任何人解决这个问题,我只想知道,如果我们能获得加载的属性文件的名称?

【问题讨论】:

  • 请添加您的测试代码,至少是您在测试中使用的注释以及application.properties 文件的确切位置。没有代码我们只能推测
  • 您可以在日志文件/控制台中获取这些详细信息。在服务器启动时,有关正在加载的配置文件的所有详细信息都记录在日志文件/控制台中。
  • @pratap 不,我们没有在日志/控制台中获取文件名
  • 如果启用调试日志,它应该显示加载的属性文件。我刚刚创建了示例 Spring Boot 应用程序并开始使用 DEBUG 日志记录,这是我在日志中看到的 2021-03-23 11:53:17.157 DEBUG 16544 --- [ main] o.s.w.c.s.StandardServletEnvironment : Adding [applicationConfig: [classpath:/application.properties]] PropertySource with search precedence immediately lower than [applicationConfigurationProperties]

标签: java spring-boot properties-file wiremock spring-boot-2


【解决方案1】:

经过一段时间的搜索和尝试,看起来ConfigurableEnvironment 就是您要查找的内容。

代码很简单。不过我认为最好直接调试和检查configurableEnvironment 值,这样您就可以根据需要调整代码(删除过滤器名称等)。

  @Autowired
  private ConfigurableEnvironment configurableEnvironment;

  @Test
  public void getProperties() {
    Map<String, Object> mapOfProperties = configurableEnvironment.getPropertySources()
        .stream()
        .filter(propertySource -> propertySource.getName()
            .contains("application-test.properties"))
        .collect(Collectors.toMap(PropertySource::getName, PropertySource::getSource));
    mapOfProperties.values()
        .forEach(System.out::println);
  }

代码将打印出来

{properties-one=value-for-properties-one, properties-two=value-for-properties-two}

使用我的 application-test.properties 值

properties-one=value-for-properties-one
properties-two=value-for-properties-two

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/env/ConfigurableEnvironment.html

【讨论】:

    【解决方案2】:

    好的,按照测试定义,请确保:

    1. 您应该使用 spring runner 运行测试(如果您使用的是 JUnit5,则使用 spring 扩展)。所以你应该把注解@RunWith(SpringRunner.class)(或@ExtendsWith(SpringExtension.class) 用于junit 5)

    2. 您使用的属性源是application-test.properties。你说过属性文件位于src/main/resources,但文件名可能暗示它应该位于src/test/resources

    【讨论】:

    • 抱歉,application-test.propertiessrc/test/resources 内部。但是,即使我在该文件中添加了任何属性.. 它也没有在应用程序中拾取。我不想对代码进行任何更改,因为我知道代码没有问题。由于某种原因没有加载正确的属性文件,这与平台有关。
    • 那么您使用的是 SpringRunner/SpringExtension 吗?没有它,整个春季基础设施将无法启动
    • 我猜应该是@ExtendWith 而不是@ExtendsWith
    猜你喜欢
    • 2020-02-21
    • 2014-05-13
    • 2016-08-20
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 2020-09-07
    相关资源
    最近更新 更多