Spring

Advanced profile management in Spring Boot

We all are aware of profile management in Spring Boot and the flexibility it provides in configuring our applications for different environments. The other powerful aspect of this is that at any given time we can have multiple active profiles. The advantage this gives is that we can mix the deployment environment profile along with business use case related profiles.

Let us assume we will have different deployments of the application in the same environment and some properties are going to change based on the deployment no matter if they are in the same environment. In such scenarios, we can have environment-specific application properties files and then each such file can override the properties which change based on different deployment.

I have defined three application properties files as shown below:

#application.properties
app.name=Default
spring.profiles.active=test,org1
#application-local.properties
app.name=Local
#application-test.yml
app:
  name: Test
---
spring:
  profiles: org1
app:
  name: Test Org1
---
spring:
  profiles: org2
app:
  name: Test Org2

Then we have a simple class AdvancedPropsDemo with the main method which prints the value of the property app.name:

@SpringBootApplication
@Component
public class AdvancedPropsDemo implements ApplicationRunner {

    @Value("${app.name}")
    String appName;

    public static void main(String[] args) {
        new SpringApplication(AdvancedPropsDemo.class).run(args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("App Name value " + appName);
    }
}

We have settest,org1 as active profile and Spring Boot has intelligently picked application-test.yml file and then picked the app.name property defined in the org1 profile. In YAML property files we can create different sections for different profiles in the same file and override the required properties in their corresponding profile section

The complete code can be found here.

Categories: Spring, Spring Boot

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.