繁体   English   中英

使用通配符使用@PropertySource(SpringBoot)读取多个属性文件

[英]Reading multiple properties files with @PropertySource (SpringBoot)using wildcard character

我想从特定位置读取多个属性文件,例如C:\config 我正在使用@PropertySource注释的帮助。 有没有办法在 Springboot 中使用一些通配符来读取这些文件,例如 (*.properties)。 所以我打算实现的是这样的

@PropertySource("*.properties") })
public class SomeClass{
}

如果没有,有没有办法以编程方式创建这些 @PropertySource("foo.properties") 或 @PropertySource("bar.properties") 并将它们提供给@PropertySources以便我可以实现这一点。

@PropertySources({
   @PropertySource("foo.properties"),
   @PropertySource("bar.properties")
})

我想在将来实现它的原因是如果我必须注入另一个属性说future.properties,我不必修改Java 文件。

这可能会帮助您:

通过命令行 arguments: 通过这种方式,您可以告诉 Spring 引导加载我们的配置文件是使用命令 arguments。 Spring Boot 提供了参数spring.config.name来设置配置文件名称,以逗号分隔。 第二个命令行参数是spring.config.location ,您必须在其中设置 Spring Boot 将找到您的外部配置文件的位置。

请参见下面的示例:

java -jar yourApp.jar --spring.config.name=application,conf 
--spring.config.location=classpath:/external/properties/,classpath:/com/yourapp/configuration/

财产来源

注释提供了一种方便的声明机制,用于将 PropertySource 添加到 Spring 的环境中。 与@Configuration 类一起使用。

支持传统和基于 XML 的属性文件格式 — 例如,“classpath:/com/myco/app.properties”或“file:/path/to/file.xml”。

不允许使用资源位置通配符(例如 **/*.properties); 每个位置都必须精确评估为 one.properties 资源。

${...} 占位符将针对已在环境中注册的任何/所有属性源进行解析。

@Configuration
@PropertySources({
    @PropertySource("classpath:test.properties"),
    @PropertySource("classpath:test1.properties")
})
public class TestConfig {
    //...
}

您可以使用通配符。 但您需要考虑已弃用 PropertyPlaceholderConfigurer。

PropertyPlaceholderConfigurer

已弃用。 从 5.2 开始; 使用 org.springframework.context.support。 PropertySourcesPlaceholderConfigurer通过利用 Environment 和 PropertySource 机制更灵活。

@Configuration
public class PropertyConfig {

    @Bean
    public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer()
            throws IOException {
        PropertyPlaceholderConfigurer propertyConfigurer = new PropertyPlaceholderConfigurer();
        propertyConfigurer.setLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/test/*.properties"));

        return propertyConfigurer;
    }

这是我在不覆盖 PropertySourcesPlaceholderConfigurer 的情况下找到的解决方案。 诀窍是使用仅用于加载工厂的虚假属性文件来实现 PropertySourceFactory。 无论如何,您必须放置一个虚假的属性文件。

@PropertySource(value = "placeholder.properties", factory = MyPropertySourceFactory.class)

此时您可以做任何事情,但您无法访问 Spring 上下文。 所以你需要使用 vanilla Java,比如使用 ClassLoader.getResources(但不支持通配符),或者你可以使用一些类路径扫描器,比如corn-cps。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM