Read Data from File in a Java Class Library Without Main Method

Viewed 81

I have a set of Java console applications which act as my system's backend Services and which I package each into their own Jars. I also have written a class library (e.g. CoreLibrary) which consists of a set of classes and no main() execution method of it's own. This CoreLibrary is a dependency for each of these Services so I bundle The same CoreLibrary Jar into each of these Services Jars.

A number of classes in my CoreLibrary use some constant value(s) (configurations) for which I had defined a class like:

public class Config {
    public static final String serverIP = "localhost:9092";
}

Now I want to shift this configuration into a config.json File like:

{
    "serverIP" : "localhost:9092"
}

and access it through something like:

public class Config {
    public static final String serverIP = getConfigValue();

    private String getConfigValue()
    {
        try {
            Reader reader = Files.newBufferedReader(pathToConfig);
            CoreConfig item = gson.fromJson(reader, CoreConfig.class);
            reader.close();
            return item.getServerIP();

        } catch (IOException e) {
            e.printStackTrace();
            return "localhost:9091";
        }
    }
}

Assuming that having a config file outside my application's Jar would allow me to change the file contents (values) each time before I run my Services Jars instead of going through the process of generating a Jar for each service every time I change this value. I also wouldn't want to load the value from the file from each Service but instead have the value loaded upon startup.

Is there a proper way to achieved this in Java (loading a value from a file from a class library on its own) ? and would it even be considered a valid code practice since item.getServerIP() may possibly produce NullPointerException if the file or json object couldn't be read ?

Note: I'm not using Spring or any such framework. It's plain Java 11 code and uses gson library.

0 Answers
Related