如何在@PropertySources中引用单独的@PropertySource来获取值

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

我有几个属性文件,在配置中进行了描述

@Configuration    
@PropertySources({
        @PropertySource(name="p1", value = "classpath:p1.properties"),
        @PropertySource(name="p2", value = "classpath:p2.properties")})

两个文件都具有相同键和不同值的属性,例如:

prop1=11
prop2=12

prop1=21
prop2=22

如何参考正确的房产来源来发挥价值?我的意思是类似

@Value("${p1.prop1}")
private int prop11;

@Bean
public SomeBean someBean() {
    return new SomeBean(prop11);
}

但是

@Value("${p1.prop1}")
是我错误的尝试。

java spring
2个回答
3
投票

你不能。两个属性源将合并到同一个 Spring Environment 中。 .properties 文件中同一键的最后声明值将覆盖同一键的任何先前值。如果您阅读@PropertySource的JavaDoc,您会发现以下声明:

如果给定的属性键存在于多个 .properties 文件中,则处理的最后一个 @PropertySource 注释将“获胜”并覆盖。


0
投票

事实上,重复的属性将被合并,并且最后读取的属性将始终被返回。但有一个办法。

首先,您必须为 2 个属性源指定不同的名称。

PropertySource(name="app1", value="app1.properties")
PropertySource(name="app2", value="app2.properties")

使用 ConfigurableEnvironment 检索所有可变属性源。使用它,您可以检索带有名称的确切属性源。该属性源将具有关联属性文件中给出的确切数据。

ConfigurableEnvironment configurableEnvironment = context.getEnvironment();
MutablePropertySources propertySources = configurableEnvironment.getPropertySources();

PropertySource<?> propertySource = propertySources.get("app1");
System.out.println(propertySource.getProperty("name"));

propertySource = propertySources.get("app2");
System.out.println(propertySource.getProperty("name"));

祝你好运!

© www.soinside.com 2019 - 2024. All rights reserved.