Yuval
Yuval

Reputation: 844

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.

Upvotes: 5

Views: 7089

Answers (1)

Andreas
Andreas

Reputation: 2521

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

Upvotes: 9

Related Questions