Java mapping properties file

YAML to Map with Spring Boot

Read the Application Properties or a YAML file as a Java Map in Spring Boot.

Overview

In a Spring or Spring Boot application, an application properties file or an application YAML file help us externalize important configurations. On top of that, the @ConfigurationProperties annotation in Spring Boot allows us to easily read and bind those configurations into Java objects.

This tutorial focuses on reading application configurations from a property or a YAML file into Java HashMap objects.

To learn more about reading application properties or YAML files into Java beans, please read Using @ConfigurationProperties in Spring Boot.

YAML or a Properties File

For this tutorial, we will work on a YAML-based configuration. However, note that all the examples in this tutorial are also applicable when using any equivalent application properties file.

Look at a typical YAML application file from a Spring Boot application.

application.yaml

spring: application: name: data-service servlet: multipart: enabled: true datasource: driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3309/test password: password username: test_user Code language: YAML (yaml)

Alternatively, We can rewrite the same configurations in a properties file.

application.properties

spring.application.name=data-service spring.servlet.multipart.enabled=true spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3309/test spring.datasource.password=password spring.datasource.username=test_userCode language: Properties (properties)

Both files contain the same configurations, and Spring Boot seamlessly works with YAML and Properties files. However, the YAML syntax is more organized and readable when we compare a properties file to an equivalent YAML file.

YAML file To Java Map

A YAML and Properties files contain sets of key and value pairs. That makes it more similar to a Map data structure. Thus, mapping a YAML or properties file into a Java HashMap is straightforward.

The following snippet demonstrates how we can use plain Java Map instances to model the Properties or YAML-based configurations we saw in the previous section.

Map application = Map.of("name", "data-service"); Map servlet = Map.of( "multipart.enabled", "true" ); Map datasource = Map.of( "driverClassName", "com.mysql.cj.jdbc.Driver", "url", "mysql://localhost:3309/test", "password", "password", "username", "test_user" );Code language: Java (java)

Interestingly, in our configuration, the sub-group of “servlet” has a nested Map. We can model the nested map using a dot notation, as seen here.

Alternatively, we change the type of the servlet map and make it a nested Map (Map of Maps).

Map> servlet = Map.of( "multipart", Map.of("enabled", "true") );Code language: Java (java)

We understood how a Map, YAML or a Properties file have similar data structures. Next, we will learn how Spring Boot @ConfigurationProperties annotation help map the application configurations from a YAML or Properties file into Java Map instances.

Читайте также:  Css styling links in div

Reading YAML or Properties as Java Map

To read application YAML or Properties configurations as a Java Map, we need to define a Map member in an @ConfigurationProperties class.

Under the root, ‘spring‘, the YAML (or Properties) file contains three nested subgroups of configurations. Let’s use the prefix ‘spring‘ to read them in separate Map instances.

@Configuration @ConfigurationProperties(prefix = "spring") public class MapProperties  < Mapapplication; Map servlet; Map datasource; // Constructor, Getter and Setter methods >Code language: Java (java)

The class has all three maps, and their names correspond to the name of the respective properties subgroups. We have also added a well-formatted toString() method that we will use to print the bean when the application starts.

* Java Map based Properties application: name=data-service servlet: multipart.enabled=true datasource: driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3309/test password=password username=test_userCode language: plaintext (plaintext)

From the output, we can see all the fields in the map are populated as expected.

Reading YAML Properties as Nested Java Map

To read nested Java Maps from a YAML file or a Properties File, we can change the type of the “servlet” field to Map>.

@Configuration @ConfigurationProperties(prefix = "spring") public class NestedMapProperties  < Mapapplication; Map servlet; Map datasource; // Constructor, Getter, and Setter methods >Code language: Java (java)

When we print the populated bean, we see that the nested Maps are correctly read from our YAML file.

* Java Map based nested Properties application: name=data-service servlet: multipart= datasource: driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3309/test password=password username=test_userCode language: plaintext (plaintext)

Reading YAML Properties as MultiValue Map

Sometimes, we may have a list of values in a YAML or a Properties Files that we want to bind in a Java Bean. Spring Boot @ConfigurationProperties allows binding a list from a YAML as a Java multi-value Map instance.

A list in a YAML file looks like this,

spring: application: name: data-service servlet: multipart: enabled: true datasource: driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3309/test password: password username: test_user profiles: active: - dev - qa - staging - prodCode language: YAML (yaml)

Or, use an in-line list with comma-separated values

spring: ## Skipped profiles: active: dev, qa, staging, prodCode language: YAML (yaml)

To read the ‘spring.profiles.active‘, we changed our Map to a multi-value Map.

@Configuration @ConfigurationProperties(prefix = "spring") public class NestedMapProperties  < Mapapplication; Map servlet; Map datasource; Map> profiles; // Constructor, Getter, and Setter methods >Code language: Java (java)

Using that, we can verify list of all the active profiles is loaded correctly.

* Java Map based nested Properties application: name=data-service servlet: multipart= datasource: driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3309/test password=password username=test_user profiles: active=[dev, qa, staging, prod]Code language: plaintext (plaintext)

Summary

This tutorial focused on Reading different keys and value pairs from a YAML or a Properties file into a Java HashMap. We understood that a YAML or a Properties file are similar to the Map data structure. Thus, we can easily bind the configurations in Java Maps.

We covered examples of reading a simple Map, Nested Map, and MultiValueMap from a YAML or equivalent application properties file.

Refer to our GitHub Repository for the complete source code.

More like this:

Источник

How to create hash map with entries from .properties file

Thanks Vishal for your quick response, i am now able to create HashMap from Properties file. Here my one more question is, if a key contains multiple values (for e.g., 2 values) in a properties file it should put 2 values into an HashMap for that key. with this code it is taking as a single string into the HashMap.

Yes, you can insert and retrieve multiple values for a single key in a HashMap. Refer this link for examples: skilledmonster.com/2013/10/21/…

Properties files are commonly read using java.util.Properties . However, since you have the same keys defined multiple times, only one of the values for each key will be available after processing the file. This means you will need to read the file manually (perhaps BufferedReader ), parse each line, and build the map you want.

Clearing the hashmap between iterations doesn’t make much sense though unless you are making a new map each iteration or doing something with the result. Again, a HashMap can only store a single value per key, so you will need another data structure to hold what it seems like you might need.

As far as I understand your question, you want to pick a set of key-value pairs from the properties file, based on the comments (##AA, ##BB etc) that you have in the properties file.

Remember, in general, the ‘key’ should not be repeated in a property file. If it is repeated, then it will always fetch the last value. For example, if you try to retrieve value for ‘key1’, it will return you ‘D1’ always. You could try naming your keys as key1AA, key2AA, key3AA, key1BB, key2BB and so on.

Also, if you try to retrieve ‘key3’, you will get the complete value ‘D3, D4’.

Here is an example I tried with your properties file:

package com; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; public class PropertiesToMap < public static void main(String[] args) < FileInputStream fis; try < fis = new FileInputStream("D://MyProps.properties"); ResourceBundle resources = new PropertyResourceBundle(fis); Mapmap = new HashMap(); //convert ResourceBundle to Map Enumeration keys = resources.getKeys(); while (keys.hasMoreElements()) < String key = keys.nextElement(); map.put(key, resources.getString(key)); >//Now you can use the 'map' object as you wish. > catch (FileNotFoundException e) < // TODO Auto-generated catch block e.printStackTrace(); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> > 

Источник

Read Properties File -Store in HashMap in Java

Challenges witjh offshore model

Thoughtcoders Logo Icon

H ow to store Java properties file ! Being a Java Developer we come across the requirement when we have to load properties and read data from the properties file. Most of the time your project configuration/credentials or server details, stored in the properties file.

How we store properties file currently? And how we should store it?

Most of the new developers load property multiple times and get data which is actually wrong practice as it takes load time for each instance. So to optimize and make this process efficient we should read properties file in one go, store in HashMap and get value from HashMap across the project.

How to store properties file or config file in HashMap ?

Here is “config.properties” file stored in project resource directory.

config.properties file

Storing properties file in HashMap – hHow to store Java properties file using hashmap
Let’s write a Java code which store & load property file using HashMap:

package UTIL; import java.io.File; import java.io.FileInputStream; import java.util.HashMap; import java.util.Map.Entry; import java.util.Properties; public class PropertyReader < private String propertyName = null; private Properties props; //This is constructor to pass property file name during object creation. public PropertyReader (String propertyName)< this.propertyName = propertyName; >//private method created to load property file private void loadProperty() < //propertyName is fileName try < props = new Properties(); FileInputStream fis = new FileInputStream(System.getProperty("user.dir") + File.separator + "resources"+ File.separator + propertyName + ".properties"); props.load(fis); >catch (Exception e) < e.printStackTrace(); >> //Public method created to access outside class.This method load property file and store Property file data in HashMap public HashMap getPropertyAsHashMap() < loadProperty(); HashMapmap = new HashMap(); for (Entry entry : props.entrySet()) < map.put((String) entry.getKey(), (String) entry.getValue()); >return map; > >

How to implement property file?

Here is the test class to test the above implementation

package UTIL; import java.util.HashMap; import org.testng.annotations.Test; public class TestProperty < @Test public void testProperty()< PropertyReader pr= new PropertyReader("config"); HashMaphs = pr.getPropertyAsHashMap(); System.out.println(hs.get("browserName")); System.out.println(hs.get("URL")); > >

Result:

Summing up, we hope this article helps you to convert the properties file in HashMap and use it across the project.

To this end, please feel free to contact us or write to us on query@thoughtcoders.com or call us on 9555902032 if you face any issue or need any additional information. You may also contact us on Facebook and LinkedIn!

Источник

Оцените статью