Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java/Gradle reading external config files

Tags:

java

gradle

My project structure looks like below. I do not want to include the config file as a resource, but instead read it at runtime so that we can simply change settings without having to recompile and deploy. my problem are two things

  1. reading the file just isn't working despite various ways i have tried (see current implementation below i am trying)
  2. When using gradle, do i needto tell it how to build/or deploy the file and where? I think that may be part of the problem..that the config file is not getting deployed when doing a gradle build or trying to debug in Eclipse.

My project structure:

myproj\
        \src
            \main
                \config
                    \com\my_app1\
                                config.dev.properties
                                config.qa.properties
                \java
                    \com\myapp1\
                                \model\
                                \service\
                                \util\
                                    Config.java
            \test              

Config.java:

public Config(){
        try {
            String configPath = "/config.dev.properties"; //TODO: pass env in as parameter
            System.out.println(configPath);
            final File configFile = new File(configPath);
            FileInputStream input = new FileInputStream(configFile);

            Properties prop = new Properties()
            prop.load(input);
            String prop1 = prop.getProperty("PROP1");
            System.out.println(prop1);
        } catch (IOException ex) {
            ex.printStackTrace();
        } 
    }   
like image 575
mike01010 Avatar asked Feb 17 '17 21:02

mike01010


People also ask

What is FileTree in Gradle?

A FileTree represents a hierarchy of files. It extends FileCollection to add hierarchy query and manipulation methods. You typically use a FileTree to represent files to copy or the contents of an archive. You can obtain a FileTree instance using Project.

How does Gradle bootRun work?

The Spring Boot gradle plugin provides the bootRun task that allows a developer to start the application in a “developer mode” without first building a JAR file and then starting this JAR file. Thus, it's a quick way to test the latest changes you made to the codebase.


1 Answers

The solution for me to be able to read an external (non-resource) file was to create my config folder at the root of the application.

myproj/
      /configs

Doing this allowed me to read the configs by using 'config/config.dev.properies'

like image 184
mike01010 Avatar answered Nov 14 '22 02:11

mike01010