How to Set Spring Profile from System Variable?
I Have a Spring Project Which Uses Another Project. Each Project Has Its Own Spring Profile Initialize from Java Code Using applicationContext. Xml and *...
I have a Spring project which uses another project. Each project has its own spring profile initialize from java code using applicationContext.xml and *.properties for each profile. I inject the profile from args[]. The problem is that second project uses the default configuration for the env from the applicationContext.xml
I can not inject the env from args[] to the second project and I tried looking for an article which will explain how Spring profile works.
- Is there a hierarchy on which it will look the profile when default is not configured at
applicationContext.xml? - Is System var stronger than
applicationContext.xmlconfiguration? - What you think is the best solution to my challenge?
Articles on that subject or even examples would be most appreciated!! Thanks in advance.
8 Answers
SPRING_PROFILES_ACTIVE is the environment variable to override/pick Spring profile
If you provide your JVM the Spring profile there should be no problems:
java -Dspring.profiles.active=development -jar yourApplication.jar
Also see Spring-Documentation:
69.5 Set the active Spring profiles
The Spring Environment has an API for this, but normally you would set a System property (spring.profiles.active) or an OS environment variable (SPRING_PROFILES_ACTIVE). E.g. launch your application with a -D argument (remember to put it before the main class or jar archive):
$ java -jar -Dspring.profiles.active=production demo-0.0.1-SNAPSHOT.jar
In Spring Boot you can also set the active profile in application.properties, e.g.
spring.profiles.active=production
A value set this way is replaced by the System property or environment variable setting, but not by the SpringApplicationBuilder.profiles() method. Thus the latter Java API can be used to augment the profiles without changing the defaults.
See Chapter 25, Profiles in the ‘Spring Boot features’ section for more information.
I normally configure the applicationContext using Annotation based configuration rather than XML based configuration. Anyway, I believe both of them have the same priority.
*Answering your question, system variable has higher priority *