configuration unification Java Spring

My application outlines are growing. I am looking for some solution to store configurations for each circuit. I think that such a configuration format would be nice :

someHost:
  test: testUrl
  local: localUrl
  dev: devUrl
  qa: qaUrl
  stage: stageUrl
  prod: prodUrl

So far, I don’t have an understanding of how to properly configure my application so that it works correctly with the necessary configurations depending on the profile. Do you have any solution?

Stack: Java, Spring Boot 2, Kubernetes

Upvotes: 0

Views: 64

Answers (3)

Nalmelune
Nalmelune

Reputation: 88

To keep format you propose you will need to create another variable where you will configure prefix.

hostPrefix: dev
someHost:
  test: testUrl
  local: localUrl
  dev: devUrl
  qa: qaUrl
  stage: stageUrl
  prod: prodUrl

Then inject it with @Value in required field with inner placeholders:

@Value("${someHost.${hostPrefix}}")
private String url;

Thats it. In current solution it will be resolved to ${someHost.dev}, which would be resolved to devUrl. You can also use spring profile for that:

@Value("${someHost.${spring.profiles}}")
private String url;

Upvotes: 1

Nalmelune
Nalmelune

Reputation: 88

Seems like you already have configuration in yml format. Then you can use spring profiles like this:

spring:
  profiles:
    active: dev
someHost:
  url: devUrl
---
spring:
  profiles: test
someHost:
  url: testUrl
---
spring:
  profiles: qa
someHost:
  url: qaUrl

And then you create @Configuration:

@Configuration
@ConfigurationProperties("someHost")
public class SomeHostConfig {

    private String url;
}

Or you can use any managed bean field and inject it with @Value:

@Value("${someHost.url}")
private String someHostUrl;

Then you run your application with profile. For example, in maven it would be:

mvn spring-boot:run -Dspring.profiles.active=dev

Upvotes: 0

Nir Levy
Nir Levy

Reputation: 12953

You can use Spring's profiles for that. Define a profile per environment, and then it can have it's own set of properties and beans

Upvotes: 0

Related Questions