Home

Wednesday, November 8, 2023

SpringBoot: Adding custom properties to ApplicationContext dynamically


While building a Spring Boot app, we often get into a situation where we need to dynamically add the properties to the ApplicationContext during application startup. Spring Boot provides an intuitive interface named ApplicationContactInitializer that can be implemented to programatically initialize the ApplicationContext or to add additional property sources to the ApplicationContext.

Below is a sample implementation of this interface to add a application run id to the application context.

    public class CustomApplicationContextInitializer implements ApplicationContextInitializer {
        private static final Logger log = LoggerFactory.getLogger(CustomApplicationContextInitializer.class);

        @Override
        public void initialize(ConfigurableApplicationContext applicationContext) {
            final ConfigurableEnvironment environment = applicationContext.getEnvironment();
            final MutablePropertySources propertySources = environment.getPropertySources();
            var dynamicProperties = new HashMap();
            dynamicProperties.put("run-id", UUID.randomUUID().toString());
            propertySources.addLast(new MapPropertySource("dynamic-properties", dynamicProperties));
        }
    }


Thereafter, we can register the CustomApplicationContextInitializer to the SpringBootApplication before calling it's run method as below:

    @SpringBootApplication
    public class Application implements CommandLineRunner{
        public static void main(String[] args){
            SpringApplication application = new SpringApplication(Application.class);
            application.addInitializers(new CustomApplicationContextInitializer());
            application.run(args);
        }
    }

Now, the run-id added during the ApplicationContext initialization will be available as part of the ApplicationContext.