Spring Boot
application.properties
programmatically override
configuration
Java

How can I override Spring Boot application.properties programmatically?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In Spring Boot applications, it's common to manage configuration properties using the application.properties or application.yml files. However, there are times when you might need to override these properties programmatically, perhaps in response to different environments, user inputs, or specific runtime conditions. This article explores various ways to achieve this.

Understanding Spring Boot's Configuration Properties

Spring Boot's configuration properties provide a powerful mechanism for controlling the application's behavior. These properties are loaded at startup and can be sourced from:

  1. application.properties or application.yml files.
  2. Environment variables.
  3. Command-line arguments.
  4. Java system properties.
  5. Dedicated configuration classes.

The order of precedence determines which source can override which, and the programmatic approach typically sits atop this hierarchy.

Programmatically Overriding Properties

Method 1: Using SpringApplication

One of the most straightforward ways to override properties programmatically is through SpringApplication. This can be achieved by calling methods on the SpringApplication instance before the application starts.

java
1import org.springframework.boot.SpringApplication;
2import org.springframework.boot.autoconfigure.SpringBootApplication;
3
4@SpringBootApplication
5public class MyApplication {
6    public static void main(String[] args) {
7        SpringApplication app = new SpringApplication(MyApplication.class);
8        app.setDefaultProperties(Collections.singletonMap("property.key", "overriddenValue"));
9        app.run(args);
10    }
11}

Method 2: Customizing ApplicationContextInitializer

Another approach involves creating a custom ApplicationContextInitializer.

java
1import org.springframework.context.ApplicationContextInitializer;
2import org.springframework.context.ConfigurableApplicationContext;
3import org.springframework.core.env.ConfigurableEnvironment;
4import org.springframework.core.env.MapPropertySource;
5
6import java.util.HashMap;
7import java.util.Map;
8
9public class CustomPropertyInitializer 
10      implements ApplicationContextInitializer<ConfigurableApplicationContext> {
11    
12    @Override
13    public void initialize(ConfigurableApplicationContext applicationContext) {
14        ConfigurableEnvironment environment = applicationContext.getEnvironment();
15        Map<String, Object> properties = new HashMap<>();
16        properties.put("property.key", "overriddenValue");
17        
18        MapPropertySource mapPropertySource = 
19              new MapPropertySource("customProperties", properties);
20        environment.getPropertySources().addLast(mapPropertySource);
21    }
22}

To integrate this initializer, you need to configure your SpringApplication:

java
1public class MyApplication {
2    public static void main(String[] args) {
3        SpringApplication app = new SpringApplication(MyApplication.class);
4        app.addInitializers(new CustomPropertyInitializer());
5        app.run(args);
6    }
7}

Method 3: Using EnvironmentPostProcessor

The EnvironmentPostProcessor is a more advanced option that allows you to post-process the Environment before the application context context is refreshed.

java
1import org.springframework.boot.SpringApplication;
2import org.springframework.boot.env.EnvironmentPostProcessor;
3import org.springframework.core.env.ConfigurableEnvironment;
4import org.springframework.core.env.PropertySource;
5
6public class EnvPropertyOverrideProcessor implements EnvironmentPostProcessor {
7
8    @Override
9    public void postProcessEnvironment(ConfigurableEnvironment environment, 
10                                       SpringApplication application) {
11        PropertySource<?> propertySource = environment.getPropertySources().get(0);
12        if (propertySource.containsProperty("some.property")) {
13            // Override logic
14            environment.getSystemProperties()
15                       .put("some.property", "newValue");
16        }
17    }
18}

This class should be registered in a META-INF/spring.factories file.

 
org.springframework.boot.env.EnvironmentPostProcessor=com.example.EnvPropertyOverrideProcessor

Summary Table

MethodClass UsedKey FeaturesContext of Use
Spring Application Default PropertiesSpringApplicationSimple and directBasic overrides at startup
Custom InitializerApplicationContextInitializerMore control with ApplicationContextFor initialization-specific properties
Post ProcessorEnvironmentPostProcessorAdvanced, operates before context refreshFor complex, environment-specific overrides

Additional Details and Considerations

  • Profiles: Remember that you can use profiles to handle different configurations for different environments.
  • Hierarchy: Understand the source precedence in Spring Boot. Programmatically setting properties will often override properties from lower-precedence sources like application.properties.
  • Security: Be cautious when overriding sensitive properties like database credentials. Ensure security measures are in place.

By selecting the appropriate method based on your specific needs, you can dynamically adjust the configuration of your Spring Boot application, tailoring it to different contexts and enhancing its adaptability.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.