【问题标题】:How to set the Profile using application.properties in Spring?如何在 Spring 中使用 application.properties 设置配置文件?
【发布时间】:2013-09-08 00:28:58
【问题描述】:

我想使用 application.properties 文件设置配置文件,其中包含以下条目:

mode=master

如何在我的 context.xml 文件中设置 spring.profiles.active? init-param 仅适用于 web.xml 上下文。

<init-param> 
    <param-name>spring.profiles.active</param-name>
    <param-value>"${mode}"</param-value>
</init-param>

【问题讨论】:

    标签: java spring


    【解决方案1】:

    您可以使用环境变量、系统变量(JVM 或应用程序的 -D 选项)或将其放入 JNDI(java:comp/env/)中。但是您不能将其放入属性文件中,因为需要在读取特定属性文件之前。

    @Profile javadocs 中有更多信息。

    另一种解决方案是创建您自己的ApplicationContextInitializer 实现,它读取某个文件并激活给定的配置文件。

    【讨论】:

      【解决方案2】:

      有几种方法可以更改活动配置文件,但都不能直接从属性文件中获取。

      • 您可以像在问题中那样使用&lt;init-param&gt;
      • 您可以在应用程序启动时提供系统参数 -Dspring.profiles.active="master"
      • 您可以通过context.getEnvironment().setActiveProfiles("container"); 以编程方式从您的ApplicationContextsetActiveProfiles(String...) 获取ConfigurableEnvironment

      您可以使用ApplicationListener 来监听上下文初始化。关于如何做到这一点的说明here。您可以使用ContextStartedEvent

      ContextStartedEvent event = ...; // from method argument
      ConfigurableEnvironment env = (ConfigurableEnvironment) event.getApplicationContext().getEnvironment();
      env.setActiveProfiles("master");
      

      您可以根据需要从属性文件中获取值"master"

      【讨论】:

      • 问题是 在我没有使用的 Spring MVC 中使用。 Spring 核心中的 等价于什么?
      • @luksmir 没有等价物。如果您控制上下文创建,则直接使用第三种方法和setActiveProfiles()
      • 感谢您的解释,在我的情况下,除了 setActiveProfiles() 之外别无选择。
      • 不幸的是,ContextStartedEvent 在应用程序上下文初始化后引发。
      • @SotiriosDelimanolis 至少不应该删除或编辑答案的最后一部分,因为事件是在上下文初始化后引发的,因此设置配置文件没有任何影响?否则人们会尝试这样做并惨败。
      【解决方案3】:

      您也可以通过System.setProperty 间接实现此目的:

      // spring.profiles file: profile1,profile2
      String anotherProfiles = Files.readString(Path.of("spring.profiles")); // or any other file
      // Even some logic can be applied here to anotherProfiles
      System.setProperty("spring.profiles.include", "dev," + anotherProfiles)
      

      可以稍微重写此示例以读取您的 application.properties 文件并获取 Spring 的指定配置文件。

      【讨论】:

        猜你喜欢
        • 2021-07-07
        • 1970-01-01
        • 1970-01-01
        • 2016-08-24
        • 1970-01-01
        • 2017-04-22
        • 1970-01-01
        • 2019-02-12
        • 2016-03-16
        相关资源
        最近更新 更多