Java 如何在Spring中使用application.properties设置概要文件?

Java 如何在Spring中使用application.properties设置概要文件?,java,spring,Java,Spring,我想使用application.properties文件和以下条目设置配置文件: mode=master 如何在my context.xml文件中设置spring.profiles.active?init param仅在web.xml上下文中工作 <init-param> <param-name>spring.profiles.active</param-name> <param-value>"${mode}"</para

我想使用application.properties文件和以下条目设置配置文件:

mode=master
如何在my 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>

spring.profiles.active
“${mode}”

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

@Profile中有更多信息


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

有几种方法可以更改活动配置文件,但没有一种方法直接从属性文件获取

  • 您可以在回答问题时使用
  • 您可以在应用程序启动时提供系统参数
    -Dspring.profiles.active=“master”
  • 您可以通过
    context.getEnvironment().setActiveProfiles(“容器”);
您可以使用
ApplicationListener
来侦听上下文初始化。有关如何执行此操作的说明。您可以使用
ContextStartedEvent

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

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

您也可以通过
系统间接获得该值。setProperty

//spring.profiles文件:profile1,profile2
String anotherProfiles=Files.readString(Path.of(“spring.profiles”);//或任何其他文件
//甚至有些逻辑也可以应用于其他配置文件
System.setProperty(“spring.profiles.include”、“dev”+其他概要文件)

此示例可以重写一点,以读取您的
应用程序.properties
文件,并获取Spring的指定配置文件。

问题在于Spring MVC中使用了我没有使用的配置文件。Spring core中的等效配置文件是什么?@luksmir没有等效配置文件。如果您控制上下文创建,请直接使用第三种方法d
setActiveProfiles()
。感谢您的解释,setActiveProfiles()没有其他选择在我的例子中。不幸的是,
ContextStartedEvent
是在应用程序上下文初始化后引发的。@SotiriosDelimanolis至少不应该删除或编辑答案的最后一部分,因为事件是在上下文初始化后引发的,因此设置配置文件没有任何影响?否则人们将尝试此方法并进行编辑我很难过。