Reputation: 3154
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>
Upvotes: 5
Views: 11473
Reputation: 1473
You also can achieve this indirectly via 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)
This sample can be rewritten a bit to read your application.properties
file and take specified profiles for Spring.
Upvotes: 0
Reputation: 279960
There are a few ways to change active profiles, none of which take directly from a properties file.
<init-param>
as you are doing in your question. -Dspring.profiles.active="master"
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.
Upvotes: 8
Reputation: 124526
You can use either a environment variable, system variable (-D option for the JVM or application) or put it in JNDI (java:comp/env/. You cannot however put it in a properties file, as it is needed before the that specific properties file is read.
There is more information in the @Profile javadocs.
Another solution is to create your own ApplicationContextInitializer implementation which reads a certain file and activates the given profile.
Upvotes: 3