TypeSafe config & HOCON + Read properties in java (with example)

By | July 6, 2016
  • Given a java application, We would like to read the property file defined in HOCON (Human-Optimized Config Object Notation.) format.
  • The property files use the suffix .conf e.g. application.conf, reference.conf.
  • We are performing following operations:
    • Reading the property file defined in reference.conf file.
    • Substituting environment variable in reference conf file.
      • java_directory = ${?JAVA_HOME}
    • We have created runnable jar to invoke main method of jar.
    • We are logging the properties using slf4j-log4j12.

TypeSafe Config Maven dependency:


Property file in HOCON format (reference.conf file)

userInfo {
	age = 30
	roles = [
database {
//Read environment variable
java_directory = ${?JAVA_HOME}

Program to read HOCON or TypfeSafe property file in java

We are loading reference.conf using ConfigFactory.load()

package org.learn.application;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;

public class Application {
	private static final Logger logger = LoggerFactory.getLogger(Application.class);
	private static final Config config = ConfigFactory.load();
	public static void main(String[] args) {
		logger.info("Start Reading HOCON file:");

		logger.info("Array of roles={}",config.getStringList("userInfo.roles"));
		logger.info("Database userName={}",config.getString("database.user"));
		logger.info("Database password={}",config.getString("database.password"));
		//Read environment variable
		if(config.hasPath("java_directory")) {
			logger.info("Java installed directory={}",config.getString("java_directory"));
		logger.info("End reading HOCON file");

Output – Read HOCON or TypeSafe config file in java

2016-07-06 21:09:58,754	[INFO] org.learn.application.Application [main] Start Reading HOCON file:
2016-07-06 21:09:58,759	[INFO] org.learn.application.Application [main] UserName=Mike
2016-07-06 21:09:58,760	[INFO] org.learn.application.Application [main] age=30
2016-07-06 21:09:58,761	[INFO] org.learn.application.Application [main] Array of roles=[guest, read-only]
2016-07-06 21:09:58,761	[INFO] org.learn.application.Application [main] Database userName=admin
2016-07-06 21:09:58,761	[INFO] org.learn.application.Application [main] Database password=admin
2016-07-06 21:09:58,761	[INFO] org.learn.application.Application [main] Java installed directory=C:\Program Files\Java\jdk1.8.0_60
2016-07-06 21:09:58,761	[INFO] org.learn.application.Application [main] End reading HOCON file


Download Code – TypeSafe/Config HOCON Java Application