Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set/override Spring / Spring Boot properties at runtime

Tags:

At the project with Spring Boot we use application.properties but need to configure some of these properties (like port number of logging level) based on an external configuration. We access the configuration via API so it is known only at runtime.

Is there a way to override or set some Spring properties at runtime (for example using a bean) and if yes how can this be achieved?

like image 505
ps-aux Avatar asked Jan 13 '15 09:01

ps-aux


People also ask

Can I change application properties at runtime spring boot?

To change properties in a file during runtime, we should place that file somewhere outside the jar. Then we tell Spring where it is with the command-line parameter –spring. config. location=file://{path to file}.

How do I override application properties in spring boot?

To override your Spring Boot application properties when it's running on Kubernetes, just set environment variables on the container. To set an environment variable on a container, first, initialise a ConfigMap containing the environment variables that you want to override.


1 Answers

You could do this with Spring Cloud Config

Just for the purpose of illustration, here's a relatively quick way to see dynamic property overrides at runtime:

First, for your bean to be able to pick up changed properties, you need to annotate it with

@RefreshScope 

Add the spring cloud dependency to your spring boot app, eg for gradle

compile group: 'org.springframework.cloud', name: 'spring-cloud-starter', version: '1.1.1.RELEASE' 

( NB You also need the spring boot actuator dependency.)

With the app running, you can view your current config at eg

http://localhost:8080/env 

eg if you have a property 'my.property' in application.properties, you'll see something like:

"applicationConfig: [classpath:/application.properties]": {   "my.property": "value1",   etc 

To change the value, POST my.property=value2 to /env as application/x-www-form-urlencoded

eg

curl -X POST http://localhost:8080 -d my.property=value2 

GET /env again and you'll see the new value appears under the "manager" section

To apply the changed properties, do an empty POST to /refresh. Now your bean will have the new value.

like image 162
Todderz Avatar answered Oct 13 '22 10:10

Todderz