Open In App

Inject a Map from a YAML File With Spring

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Spring Framework provides a powerful way to configure applications using external configuration files. YAML (YAML Ain't Markup Language) is a popular format for configuration files due to its readability and ability to represent complex data structures easily. In this article, we will explore how to inject a Map from a YAML file into a Spring application.

Prerequisites:

Before we begin, we should have the following set up:

  • Java Development Kit (JDK) 8 or higher
  • Maven or Gradle for dependency management
  • Spring Boot (or Spring Framework

Steps to Inject a Map from a YAML File with Spring

  • Step 1: Create a Spring Boot project using Spring Initializr.
  • Step 2: Add dependencies like spring-boot-starter and spring-boot-configuration-processor to your project.
  • Step 3: Create an application.yml file with the required configuration.
  • Step 4: Create a configuration class using @ConfigurationProperties to bind the YAML properties to a Map.
  • Step 5: Create a REST controller to access the injected map from the configuration.
  • Step 6: Write a test class to verify the map injection with @SpringBootTest.
  • Step 7: Run the application and access the endpoint to see the injected map in JSON format.
  • Step 8: Run the tests using Maven to ensure the setup is working correctly.

Implementation to Inject a Map from a YAML File with Spring

Below are the implementation steps to inject a map from a YAML file with the Spring application. For this article, we will use Spring Initializr to generate the project with the necessary dependencies.

Step 1: Create a Spring Boot Project

First we will create a new Spring Boot project using Spring Initializr.

Note: To know, how to create a Spring Boot Project, refer this article: How to create a Spring Boot Project using Spring Initializr

Step 2: Add Dependencies

Include the below dependencies into the spring boot project:

  • Spring Web
  • Spring Configuration Processor (optional for IDE support)
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
  • Now, click on the "Generate" button to download the spring boot project as a ZIP file.
  • Next, extract the ZIP file and open the project in your favorite IDE (like IntelliJ IDEA or Eclipse).

Step 3: Create the YAML Configuration File

Create a YAML configuration file named application.yml in the src/main/resources directory of the Spring Boot application.

Here is an example structure:

# application.yml

spring:
application:
name: mapyaml # Name of the application

myconfig:
items:
item1: "Value 1"
item2: "Value 2"
item3: "Value 3"
  • spring.application.name: Sets the name of the application.
  • myconfig.items: Defines a map named items under the myconfig prefix, containing key-value pairs.

In this example, we define a myconfig property, which contains a nested map called items with three entries.

Step 4: Create a Configuration Class

Next, create a configuration class that binds the YAML properties to a Map. Here, we will use the @ConfigurationProperties annotation for this purpose.

Example Configuration Class:

Java
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@ConfigurationProperties(prefix = "myconfig")
public class MyConfig {

    private Map<String, String> items;

    public Map<String, String> getItems() {
        return items;
    }

    public void setItems(Map<String, String> items) {
        this.items = items;
    }
}
  • The @ConfigurationProperties annotation binds the properties defined in the YAML file under the specified prefix (myconfig in this case).
  • The items field is a Map that will store the key-value pairs defined in the application.yml file.

Step 5: Create a Controller to Access the Map

We can now access the injected Map in our application by creating a simple controller named MyController.java.

Example REST Controller:

Java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class MyController {

    private final MyConfig myConfig;

    public MyController(MyConfig myConfig) {
        this.myConfig = myConfig;
    }

    @GetMapping("/items")
    public Map<String, String> getItems() {
        return myConfig.getItems();
    }
}
  • The MyController class is annotated with @RestController, making it a Spring MVC controller.
  • It has a constructor that accepts the MyConfig bean, allowing access to the injected map.
  • The /items endpoint returns the contents of the injected Map in JSON format.

Step 6: Testing the Configuration

Now, let’s create a test class to verify that our configuration is working correctly. Create in the specified directory:

Java
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest
public class MyConfigTest {

    @Autowired
    private MyConfig myConfig;

    @Test
    void testMapInjection() {
        assertThat(myConfig.getItems()).containsEntry("item1", "Value 1")
                                        .containsEntry("item2", "Value 2")
                                        .containsEntry("item3", "Value 3");
    }
}
  • @SpringBootTest: Loads the application context for the test.
  • assertThat(): Verifies that the injected map contains the expected entries.

Step 7: Run the Application

Now, run the application from the IDE or using the command line:

mvn spring-boot:run

After running successfully, now access the endpoint by navigating to http://localhost:8080/items in the web browser or using a tool like Postman or cURL.

Expected Output:

You should see a JSON representation of the injected Map:

{
"item1": "Value 1",
"item2": "Value 2",
"item3": "Value 3"
}

Step 8: Run the Tests

Now, we can run the tests using your IDE or by executing the following command in the terminal:

mvn test

If everything is set up correctly, you should see the test pass successfully, indicating that the map has been injected as expected.


Similar Reads