Skip to main content

Dynamically Loading YAML Files in Spring Boot with Java

In modern applications, configuration plays a crucial role in maintaining flexibility and modularity. Often, we need to load properties from multiple YAML files, organized across nested directories, to ensure scalability and modular configuration. In this blog, we’ll explore how to dynamically load all YAML files from a specific directory structure and merge their properties into a single configuration object.


Use Case

Imagine we have a configuration directory like this:

src/main/resources

├── application.yml

├── configs

│   ├── environment

│   │   ├── dev.yml

│   │   ├── qa.yml

│   ├── features

│   │   ├── feature1.yml

│   │   ├── feature2.yml


We want to load all YAML files under the configs directory (including subdirectories), merge them, and make the properties available for use in our Spring Boot application.


Implementation

1. Dynamic YAML Loader

We will create a utility class to dynamically load and merge all YAML files into a single Properties object.

package com.example.config;


import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;

import org.springframework.core.io.Resource;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;


import java.io.IOException;

import java.util.Properties;


public class DynamicYamlLoader {


    public static Properties loadYamlFiles(String basePath) throws IOException {

        Properties combinedProperties = new Properties();

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();


        // Use '**' to include all nested directories and `.yml` files

        Resource[] resources = resolver.getResources(basePath + "/**/*.yml");


        for (Resource resource : resources) {

            if (resource.exists() && resource.isReadable()) {

                YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();

                yamlFactory.setResources(resource);

                Properties yamlProperties = yamlFactory.getObject();

                if (yamlProperties != null) {

                    combinedProperties.putAll(yamlProperties);

                }

            }

        }


        return combinedProperties;

    }

}

2. Spring Configuration Loader

To integrate this loader into Spring, we’ll create a configuration class that loads the properties and makes them available in the application context.


package com.example.config;


import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;


import java.io.IOException;

import java.util.Properties;


@Configuration

public class AppConfig {


    @Bean

    public Properties dynamicProperties() throws IOException {

        // Specify the base directory

        String basePath = "classpath:/configs";

        return DynamicYamlLoader.loadYamlFiles(basePath);

    }

}


3. Example YAML Files

Here are some sample YAML files to simulate a realistic use case:

configs/environment/dev.yml:


app:

  name: DemoApp

  environment: development

logging:

  level: DEBUG

configs/features/feature1.yml:

feature1:

  enabled: true

  maxRetries: 3

configs/features/feature2.yml:

feature2:

  enabled: false

  timeout: 5000

4. Accessing Properties

You can now access the combined properties in your application. For example:

package com.example.service;


import org.springframework.stereotype.Service;


import java.util.Properties;


@Service

public class PropertyService {


    private final Properties properties;


    public PropertyService(Properties properties) {

        this.properties = properties;

    }


    public void printProperties() {

        System.out.println("App Name: " + properties.getProperty("app.name"));

        System.out.println("Feature1 Enabled: " + properties.getProperty("feature1.enabled"));

        System.out.println("Feature2 Timeout: " + properties.getProperty("feature2.timeout"));

    }

}


When running the application, the output will be:

App Name: DemoApp

Feature1 Enabled: true

Feature2 Timeout: 5000


Explanation

  1. Recursive File Loading:

    • The PathMatchingResourcePatternResolver ensures all YAML files under the specified path (including subdirectories) are discovered.
  2. Merging Properties:

    • Using Properties.putAll() allows us to combine properties from all YAML files. If duplicate keys exist, the last-loaded file overwrites the earlier values.
  3. Spring Integration:

    • By declaring a @Bean, we make the combined properties available for dependency injection.

 


 


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...

How to Identify High-Growth Stocks: Key Metrics and Analysis

Identifying high-growth stocks can significantly enhance your investment portfolio's performance. By analyzing key financial metrics, growth indicators, and market opportunities, you can pinpoint companies with the potential for exceptional returns. This blog outlines the critical factors to consider when selecting high-growth stocks. Key Metrics for High-Growth Stocks 1. Earnings Growth Consistent earnings growth is a hallmark of high-growth stocks. Look for companies with a double-digit EPS (Earnings Per Share) growth rate over several years, indicating strong profitability. 2. Revenue Growth Revenue growth shows the company’s ability to expand its market share or increase sales. Look for annual revenue growth rates above 15-20% . 3. Return on Equity (ROE) ROE measures how effectively a company uses shareholders' equity to generate profit. A high ROE (above 15-20% ) is ideal for high-growth companies. 4. Profit Margins Gross...