如何在Spring中使用application.properties设置配置文件? [英] How to set the Profile using application.properties in Spring?
问题描述
我想使用application.properties文件设置配置文件,条目为:
I would like to set the Profile using application.properties file with the entry:
mode=master
如何在我的context.xml文件中设置spring.profiles.active? init-param仅适用于web.xml上下文。
How to set spring.profiles.active in my context.xml file? init-param works only in a web.xml context.
<init-param>
<param-name>spring.profiles.active</param-name>
<param-value>"${mode}"</param-value>
</init-param>
推荐答案
有几种方法可以更改活动配置文件,没有其中一个直接来自属性文件。
There are a few ways to change active profiles, none of which take directly from a properties file.
- 您可以使用
< init-param>
正如你在问题中所做的那样。 - 您可以在应用程序启动时提供系统参数
-Dspring.profiles.active =master
- 您可以从
ApplicationContext
和setActiveProfiles获取
以编程方式使用ConfigurableEnvironment
(String ...)context.getEnvironment()。setActiveProfiles(container);
- You can use the
<init-param>
as you are doing in your question. - You can provide a system parameter at application startup
-Dspring.profiles.active="master"
- You can get the
ConfigurableEnvironment
from yourApplicationContext
andsetActiveProfiles(String...)
programmatically withcontext.getEnvironment().setActiveProfiles("container");
您可以使用 ApplicationListener
来监听上下文初始化。有关如何执行此操作的说明此处。您可以使用 ContextStartedEvent
You can use an ApplicationListener
to listen to context initialization. Explanations on how to do that here. You can use a ContextStartedEvent
ContextStartedEvent event = ...; // from method argument
ConfigurableEnvironment env = (ConfigurableEnvironment) event.getApplicationContext().getEnvironment();
env.setActiveProfiles("master");
您可以获得价值master
根据您认为合适的属性文件。
You can get the value "master"
from a properties file as you see fit.
这篇关于如何在Spring中使用application.properties设置配置文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!