Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch Spring profiles on runtime?

Currently I inject to my application properties via @Value and it works just fine. Now I want my application to support more than one configuration, which means its @Value should return different value each time.

I read about spring profiles, but I couldn't understand how can I switch profile on runtime. Is it even possible?

What I really need is to load all of the configuration when the server starts and choose its profile dynamically when a request arrives - each request should have one set of configurations.

like image 849
Yuval Avatar asked Dec 04 '18 09:12

Yuval


People also ask

How do you set Spring profiles active dynamically?

22.2 Programmatically setting profiles You can programmatically set active profiles by calling SpringApplication. setAdditionalProfiles(...) before your application runs. It is also possible to activate profiles using Spring's ConfigurableEnvironment interface.

Where is active profile in Spring boot?

application. properties - Configuration for application. Active profile is set in application.


1 Answers

Switching Spring profiles during runtime is not a good practice. Spring profile is meant to be used as a way to manage your application across different environments.

Spring Profiles provide a way to segregate parts of your application configuration and make it be available only in certain environments

If you have a variable that needs to change dynamically for every incoming requests, consider these several options:

  • Store the value in DB, cache on start, and fetch based on the incoming request parameters/body
  • Infer the value from incoming request parameters/body
  • Store all the possible values in properties file, load on start, and select based on incoming request parameters/body
  • Store all the possible values as enum/constants and select bsaed on incoming request parameters/body
like image 133
Andreas Avatar answered Oct 13 '22 20:10

Andreas