Skip to main content

Dynamic Configuration Loading in Spring Boot: Handling Multiple Variants with a Primary Configuration

Shop Christmas Products Now

In this post, we'll discuss how to dynamically load and manage configurations in a Spring Boot application based on various variants or profiles. This approach is especially useful in scenarios like A/B testing, where each variant may have distinct configuration requirements, but there's also a need for a primary or default configuration.

We’ll demonstrate the solution using a generalized example while outlining the key concepts.


Use Case

Imagine you have a Spring Boot application that needs to load different configurations for various feature variants dynamically, while also maintaining a default configuration as the fallback. The system should:

  1. Dynamically load configuration properties from multiple sources.
  2. Register variant-specific configurations as Spring beans.
  3. Ensure the default configuration is marked as primary for injection wherever no variant is specified.
  4. Provide a mechanism to retrieve a specific configuration based on the variant name.

The Architecture

  1. Configuration Loading: Load configurations from external YAML files.
  2. Dynamic Bean Registration: Register each configuration variant as a Spring bean at runtime.
  3. Dynamic Bean Lookup: Provide an interface to fetch a specific variant’s configuration.



Implementation

1. Configuration Properties Model


@ConfigurationProperties(prefix = "feature-config") @Data @NoArgsConstructor @AllArgsConstructor public class FeatureConfigProperties { private Map<String, String> settings; }


This model represents a generic configuration for a feature. Each variant may have different values for the settings map.




2. Loading Configurations from YAML




# default.yml feature-config: settings: key1: "default-value1" key2: "default-value2" # variant1.yml feature-config: settings: key1: "variant1-value1" key2: "variant1-value2"



Assume these YAML files are stored in directories categorized by environment (e.g., dev, prod) and variant.


3. YAML Resource Loader

This component loads YAML properties for each variant.

@Slf4j public class YamlResourceLoader { private static final String CONFIG_BASE_PATH = "classpath:/config"; public Map<String, Properties> loadAllVariantProperties(String environment) { Map<String, Properties> resultMap = new TreeMap<>(); String searchPath = CONFIG_BASE_PATH + "/" + environment + "/**/*.yml"; try { Resource[] resources = new PathMatchingResourcePatternResolver().getResources(searchPath); for (Resource resource : resources) { if (resource.exists() && resource.isReadable()) { String variant = extractVariantFromPath(resource.getURL().getPath(), environment); Properties properties = loadYamlProperties(resource); resultMap.put(variant, properties); } } } catch (IOException e) { throw new RuntimeException("Failed to load variant properties", e); } return resultMap; } private Properties loadYamlProperties(Resource resource) { YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean(); yamlFactory.setResources(resource); return yamlFactory.getObject(); } private String extractVariantFromPath(String path, String environment) { return path.substring(path.indexOf(environment + "/") + (environment + "/").length(), path.indexOf('/')); } }


4. Dynamic Bean Registration

This component dynamically registers beans for each variant.


@Slf4j public class DynamicConfigurationRegistrar { private static final String DEFAULT_VARIANT = "default"; private final ApplicationContext applicationContext; public DynamicConfigurationRegistrar(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } public void registerConfigurationBeans(Map<String, Properties> configMap, Environment environment) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) applicationContext.getAutowireCapableBeanFactory(); for (Map.Entry<String, Properties> entry : configMap.entrySet()) { String variant = entry.getKey(); Properties properties = entry.getValue(); registerConfigurationBean(registry, properties, FeatureConfigProperties.class, variant); } } private void registerConfigurationBean(BeanDefinitionRegistry registry, Properties properties, Class<?> clazz, String variant) { Binder binder = new Binder(new MapConfigurationPropertySource(properties)); Object beanInstance = binder.bind("feature-config", clazz).orElseThrow(); GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(clazz); beanDefinition.setInstanceSupplier(() -> beanInstance); if (DEFAULT_VARIANT.equals(variant)) { beanDefinition.setPrimary(true); } String beanName = clazz.getSimpleName() + "_" + variant; registry.registerBeanDefinition(beanName, beanDefinition); log.info("Registered configuration bean: {}", beanName); } }


5. Dynamic Configuration Lookup

A service to fetch beans dynamically by variant name


@Service public class ConfigurationLookupService { private final ApplicationContext applicationContext; @Autowired public ConfigurationLookupService(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } public <T> T getConfigurationBean(String variant, Class<T> configClass) { String beanName = configClass.getSimpleName() + "_" + variant; if (applicationContext.containsBean(beanName)) { return applicationContext.getBean(beanName, configClass); } else { throw new RuntimeException("Configuration bean for variant '" + variant + "' not found."); } } }




6. Putting It All Together

A BeanFactoryPostProcessor to integrate the loader and registrar:


@Slf4j @Configuration public class ConfigurationLoader { @Bean public YamlResourceLoader yamlResourceLoader() { return new YamlResourceLoader(); } @Bean public DynamicConfigurationRegistrar dynamicConfigurationRegistrar(ApplicationContext context) { return new DynamicConfigurationRegistrar(context); } @Bean public BeanFactoryPostProcessor configurationPostProcessor( YamlResourceLoader loader, DynamicConfigurationRegistrar registrar) { return beanFactory -> { String environment = "prod"; // You can fetch this dynamically Map<String, Properties> configMap = loader.loadAllVariantProperties(environment); StandardEnvironment env = beanFactory.getBean(StandardEnvironment.class); registrar.registerConfigurationBeans(configMap, env); log.info("Dynamic configurations loaded successfully."); }; } }



Usage

Fetch configuration for a specific variant dynamically:


@Autowired private ConfigurationLookupService lookupService; public void useConfig() { FeatureConfigProperties defaultConfig = lookupService.getConfigurationBean("default", FeatureConfigProperties.class); FeatureConfigProperties variant1Config = lookupService.getConfigurationBean("variant1", FeatureConfigProperties.class); log.info("Default config: {}", defaultConfig.getSettings()); log.info("Variant1 config: {}", variant1Config.getSettings()); }




Conclusion

This approach provides a clean, extensible way to manage configuration variants dynamically. Key benefits include:

  1. Scalability: Easily add new variants without code changes.
  2. Separation of Concerns: Configuration and business logic are decoupled.
  3. Primary Fallback: Ensures a default configuration is always available.

You can adapt this design to any multi-variant scenario, making it ideal for dynamic and modular application architectures.





Comments

Popular posts from this blog

Mastering Java Logging: A Guide to Debug, Info, Warn, and Error Levels

Comprehensive Guide to Java Logging Levels: Trace, Debug, Info, Warn, Error, and Fatal Comprehensive Guide to Java Logging Levels: Trace, Debug, Info, Warn, Error, and Fatal Logging is an essential aspect of application development and maintenance. It helps developers track application behavior and troubleshoot issues effectively. Java provides various logging levels to categorize messages based on their severity and purpose. This article covers all major logging levels: Trace , Debug , Info , Warn , Error , and Fatal , along with how these levels impact log printing. 1. Trace The Trace level is the most detailed logging level. It is typically used for granular debugging, such as tracking every method call or step in a complex computation. Use this level sparingly, as it can generate a large volume of log data. 2. Debug The Debug level provides detailed information useful during dev...

Choosing Between Envoy and NGINX Ingress Controllers for Kubernetes

As Kubernetes has become the standard for deploying containerized applications, ingress controllers play a critical role in managing how external traffic is routed to services within the cluster. Envoy and NGINX are two of the most popular options for ingress controllers, and each has its strengths, weaknesses, and ideal use cases. In this blog, we’ll explore: How both ingress controllers work. A detailed comparison of their features. When to use Envoy vs. NGINX for ingress management. What is an Ingress Controller? An ingress controller is a specialized load balancer that: Manages incoming HTTP/HTTPS traffic. Routes traffic to appropriate services based on rules defined in Kubernetes ingress resources. Provides features like TLS termination, path-based routing, and host-based routing. How Envoy Ingress Controller Works Envoy , initially built by Lyft, is a high-performance, modern service proxy and ingress solution. Here's how it operates in Kubernetes: Ingress Resource : You d...

Distributed Transactions in Microservices: Implementing the Saga Pattern

Managing distributed transactions is one of the most critical challenges in microservices architecture. Since microservices operate with decentralized data storage, traditional ACID transactions across services are not feasible. The Saga Pattern is a proven solution for ensuring data consistency in such distributed systems. In this blog, we’ll discuss: What is the Saga Pattern? Types of Saga Patterns : Orchestration vs. Choreography How to Choose Between Them Implementing Orchestration-Based Saga with Spring Boot An Approach to Event-Driven Saga with Kafka 1. What is the Saga Pattern? The Saga Pattern breaks a long-running distributed transaction into a series of smaller atomic transactions , each managed by a microservice. If any step fails, compensating actions are performed to roll back the preceding operations. Example: In an e-commerce system , a customer places an order: Payment is processed. Inventory is reserved. Shipping is scheduled. If inventory reservation fails, the paym...