Open In App

Inject a Map from a YAML File With Spring

An Application YAML file or application properties file in a Spring or Spring Boot application demonstrates the externalization of important settings. We can read and bind those configurations into Java objects to Spring Boot’s @ConfigurationProperties annotation. We will work on a YAML-based configuration. We may use any similar application properties file with any of the examples in this article.

Implementation of Injecting a Map from a YAML File with Spring

Below are the steps to inject a map from a YAML file with the Spring application.



Step 1: Spring Framework’s YAML Files

Spring developers frequently use YAML files to hold external configuration data. The SnakeYAML is used by Spring to parse YAML documents, which serve as a substitute for properties. Let’s quickly see what a common YAML file looks like:

server:
port: 8090
application:
name: myapplication
url: http://myapplication.com

Step 2: Inject a Map from a YAML File

Data externalization has been elevated by Spring Boot by using @ConfigurationProperties annotation. The purpose of this annotation is to make it simple to add external attributes to Java objects straight from configuration files. We will start by defining a few key-value attributes for the application.yml:



server:
application:
name: InjectMapFromYAML
url: http://injectmapfromyaml.dev
description: Inject a Map from a YAML File with Spring
config:
ips:
- 10.10.10.10
- 10.10.10.11
- 10.10.10.12
- 10.10.10.13
filesystem:
- /dev/root
- /dev/md2
- /dev/md4
users:
root:
username: root
password: rootpass
guest:
username: guest
password: guestpass

Step 3: Create a bean class

Next, we are going to develop a bean class called ServerProperties, which will include the logic for binding our configuration parameters to Maps:




import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
  
import java.util.List;
import java.util.Map;
  
@Component
@ConfigurationProperties(prefix = "server")
public class ServerProperties {
  
    private Map<String, String> application;
    private Map<String, List<String>> config;
    private Map<String, Credential> users;
  
    // getters and setters
  
    // Inner class representing credential properties
    public static class Credential {
          
        private String username;
        private String password;
          
        // getters and setters
          
    }
}

Step 4: Inject the ApplicationProps bean into a test class

The ApplicationProps bean is then injected into a test class, and we check to see that our profiles YAML list is injected as a ListObject correctly:




@ExtendWith(SpringExtension.class)
@ContextConfiguration(initializers = ConfigDataApplicationContextInitializer.class)
@EnableConfigurationProperties(value = ApplicationProps.class)
class YamlSimpleListUnitTest {
  
    @Autowired
    private ApplicationProps applicationProps;
  
    @Test
    public void whenYamlList_thenLoadSimpleList() {
        // Assertions for the "profiles" property in ApplicationProps
        assertThat(applicationProps.getProfiles().get(0)).isEqualTo("dev");
        assertThat(applicationProps.getProfiles().get(4).getClass()).isEqualTo(Integer.class);
        assertThat(applicationProps.getProfiles().size()).isEqualTo(5);
    }
}

Step 5: Test a YAML properties

Lastly, we will verify that our YAML attributes have been correctly inserted as Maps:




import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
  
@RunWith(SpringRunner.class)
@SpringBootTest
class MapFromYamlIntegrationTest {
  
    @Autowired
    private ServerProperties serverProperties;
  
    @Test
    public void whenYamlFileProvidedThenInjectSimpleMap() {
        // Assertions for the "server.application" properties
        assertThat(serverProperties.getApplication())
          .containsOnlyKeys("name", "url", "description");
  
        assertThat(serverProperties.getApplication()
          .get("name")).isEqualTo("InjectMapFromYAML");
    }
  
    @Test
    public void whenYamlFileProvidedThenInjectComplexMap() {
        // Assertions for the "server.config" properties
        assertThat(serverProperties.getConfig()).hasSize(2);
  
        assertThat(serverProperties.getConfig()
          .get("ips")
          .get(0)).isEqualTo("10.10.10.10");
  
        // Assertions for the "server.users" properties
        assertThat(serverProperties.getUsers()
          .get("root")
          .getUsername()).isEqualTo("root");
    }
}


Article Tags :