Search code examples
javasnakeyaml

how to load a configuration from a .yaml file to a class in java?


I am using the snakeyaml library to load the yaml file but it shows me an error

enter image description here

this is the code from my Settings class, it has an Database object which represents the database settings

package com.example;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.yaml.snakeyaml.Yaml;

public class Settings {
    private final static InputStream file;
    private final static Settings parsedSettings;
    public Database database;
    static {
        try {
            file = new FileInputStream("./src/main/java/com/example/settings.yaml");
            Yaml yaml = new Yaml();
            parsedSettings = yaml.loadAs(file, Settings.class);
        } catch(FileNotFoundException ex) {
            ex.printStackTrace();
            throw new RuntimeException("Settings file not found or cannot be readed");
        }
    }
    public Settings(){
        this.database = parsedSettings.database;
    }

    public class Database {
        private String driver;
        private String user;
        private String password;
        private String host;
        private int    port;
        private String name;

        private Database(String driver, String user, String password, String host, int port, String name){
            this.driver   = driver;
            this.user     = user;
            this.password = password;
            this.host     = host;
            this.port     = port;
            this.name     = name;
        }

        public String getDriver() {
            return this.driver;
        }
        public String getUser() {
            return this.user;
        }
        public String getPassword() {
            return this.password;
        }
        public String getHost() {
            return this.host;
        }
        public int getPort() {
            return this.port;
        }
        public String getDatabaseName() {
            return this.name;
        }
    }
}

And this is my settings.yaml file:

database:
  driver: mysql
  user: root
  password:
  host: localhost
  port: 3306
  name: java_messages_app

I'm not using any framework, I'm only using libraries

I don't know if I have to load in the constructor or in static way.

Sorry for my english, I'm using google translator


Solution

  • You can use apache commons configuration:-

    <dependency>
      <groupId>commons-configuration</groupId>
      <artifactId>commons-configuration</artifactId>
      <version>1.6</version>
    </dependency>
    

    This has to be inside your code where you want the values to be read :-

    PropertiesConfiguration config = new PropertiesConfiguration();
    config.load(PROPERTIES_FILENAME);
    config.getInt("key");
    

    Assuming your yml looks like this :-

    key: value