将 @PropertySource 限制为 spring 中的特定 @Configuration 类

Restricting @PropertySource to specific @Configuration classes in spring

我有以下 属性 个文件:

根据最后三个文件,我有 3 <Name>Property 类 格式如下。

@Configuration
@PropertySource("file:<filepath>")
public class ServiceAProperties {

    private final Environment env;

    @Autowired
    public ServiceAProperties (Environment env) {
        this.env = env;
    }

    public String getTest() {
        String test = env.getProperty("application.test"); // Accessible - Not Intended
        test = env.getProperty("common.test");             // Accessible - Not Intended
        test = env.getProperty("servicea.test");           // Accessible - Intended
        test = env.getProperty("password.test");           // Accessible - Not Intended
        return env.getProperty("servicea.test");
    }
}

出于某种原因,即使我只有各自的 Property 类 标记了它们特定的 属性 文件路径,它们也会从其他文件中获取路径并将其添加到环境。

如何确保我的环境仅从我指定的文件生成?

@PropertySourcespring docs 说:

Annotation providing a convenient and declarative mechanism for adding a PropertySource to Spring's Environment. To be used in conjunction with @Configuration classes.

这意味着只有一个 Spring 环境。当你有多个 类 用这个注释注释时,它们将始终为相同的环境做出贡献,因为只有一个。

因此,为了回答您的问题,在您的情况下,环境将始终充满来自所有具有 @Configuration@PropertySource 注释的 类 的数据。

为了用您指定的数据填充环境,您可以使用 profile specific properties。您可以在多个配置文件中分离数据并选择将被激活的配置文件(以及哪些数据将在环境中访问)。

我正在分享我自己的解决方案,因为我找不到可接受的答案。

使用 new ResourcePropertySource("classpath:<location>") 允许您使用各自的对象加载多个单独的 属性 文件。

加载后,可以像以前一样访问配置propertiesObj.getProperty("propKey")