0

I am using jdk 8 and am trying to externalise database connection variables in my java application. There is one way to do this like System.getEnv("key") but I dont need to use this.

Can anyone help to achieve this without Spring.

my configuration,

dbHost: localhost
dbPort: 8091
bucketName: demo_bucket

Kindly provide your inputs.

SST
  • 2,054
  • 5
  • 35
  • 65
  • 1
    Just use a properties file see https://docs.oracle.com/javase/7/docs/api/java/util/Properties.html – Scary Wombat Mar 28 '18 at 07:13
  • @ScaryWombat When we use Properties, it will bind the configuration value with in the jar OR war but I need to access the value from outside.. How to do this?? – SST Mar 28 '18 at 09:19
  • You can load Properties file from an InputStream which could be any old file – Scary Wombat Mar 28 '18 at 23:45
  • you can externalize the configs using some service discovery databases like zookeeper,consul or etcd. – wandermonk May 24 '19 at 06:29

1 Answers1

0

You can use Properties object in java for inline configuration.

java.util.Properties dbConfig = new java.util.Properties();
dbConfig.put("url", <your_db_url>);
dbConfig.put("user", <db_user>);
dbConfig.put("password", <db_user_password>);

pass dbConfig object to your factory that builds your connection object.

Another way, You can use yml file to store your configuration and then read that file and create a configuration object, configuration object pass across your application architecture. It gives the flexibility to manage your configuration according to your criteria.

eigenharsha
  • 2,051
  • 1
  • 23
  • 32
  • I dont want to bind this configuration in the generated war OR jar. I need to read this configuration from outside of the application like /etc/properties – SST Mar 28 '18 at 07:31
  • yml file is a better option to store configuration outside of your project. hope this help... – eigenharsha Mar 28 '18 at 07:34
  • you can go through my demo application on https://github.com/eigenharsha/jersey-mvc-jsp-freemarker-with-embedded-tomcat – eigenharsha Mar 28 '18 at 07:35
  • Thanks @eigenharsha! But in this application we need to give the path " configuration = new YMLConfiguration().getYMLConfigration(System.getProperty("user.dir") + "/configuration.yml"); ". Is there any other way to do this?? – SST Mar 28 '18 at 07:50
  • It is required to get the path of the configuration file by the app, if you are not interested to configure the directory structure path... then you go for system environment variable and create an env variable that has configuration file location..... this is just kind of patch...I'm not getting any specific idea about this. – eigenharsha Mar 28 '18 at 10:05