Spring-boot property value used in another property key

1.3k views Asked by At

In my spring boot project, I want to use a property value in another property key:

server.mode=mock

server.protocol.mock=http
server.host.mock=my.host-mock.org
...

server.protocol.prod=https
server.host.prod=my.host-prod.org
...

I want to depending on "server.mode" value use the related property key server.protocol.{value}

How could I do this? Thanks for help

2

There are 2 answers

0
balias On

This can be achieved using the following format while fetching the value in code (or the correpsonding xml) where you are using it:

@Value("${server.protocol.${server.mode}}")
private String mode;
0
OTheriault On

You can use spring profiles, where you can setup different property configurations for different deployment environments.

Using property files, you can create a property file per profile and then have spring boot use the right property configuration depending on the active profile.

project structure

application-dev.properties

server.scheme=http
server.host=my.host-mock.org

application-prod.properties

server.scheme=http
server.host=my.host-mock.org

You would then have to tell spring boot which profile to use by setting it in the spring.profiles.active property. When deploying to the cloud with application manifests (like Cloud Foundry or Kubernetes), then it is convenient to set this via an environment variable SPRING_PROFILES_ACTIVE.

See the official spring-boot documentation for more information about profiles.