Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the Profile using application.properties in Spring?

Tags:

java

spring

I would like to set the Profile using application.properties file with the entry:

mode=master

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>
like image 353
luksmir Avatar asked Sep 04 '13 13:09

luksmir


1 Answers

There are a few ways to change active profiles, none of which take directly from a properties file.

  • 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 your ApplicationContext and setActiveProfiles(String...) programmatically with context.getEnvironment().setActiveProfiles("container");

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");

You can get the value "master" from a properties file as you see fit.

like image 158
Sotirios Delimanolis Avatar answered Oct 25 '22 02:10

Sotirios Delimanolis