简体   繁体   中英

Get variable from config.properties thoughtout Java app

I'm loading variables from a config.properties in my main class but how do I call these variables though out my app in these other files? I need to get hostName from my config.properties in multiple classes and the other java files as shown in my screenshot.

This code is in my RFIDMainDlg.java file, I want to call the value of hostName in my RFIDBase.java file

Screenshot

 public static void main(String args[]) throws IOException  {

       Properties prop=new Properties();
       FileInputStream ip= new FileInputStream("resources/config.properties");
       prop.load(ip);
                  
       String hostName = prop.getProperty("hostName");
       System.out.println(hostName);
       

You can use a Singleton like this https://www.codeproject.com/articles/189489/java-properties-example-using-singleton-pattern (sorry for the ugly website, but it's a basic concept), it's not necessary but it's one of your options.

The solution on that page worked

package rfidsample;

import java.io.*;
import java.util.Properties;

public class RFIDGetPropertyValues {
    
static private RFIDGetPropertyValues _instance = null;
    String hostName = null;
    String port = null;
    String intensity = null;
    String user = null;
    String pass = null;
    String jdbc = null;
    String driver = null;
    String instance = null;
     
    protected RFIDGetPropertyValues(){
    try{
        InputStream file = new FileInputStream(new File("resources/config.properties")) ;
        Properties props = new Properties();
        props.load(file);
        hostName = props.getProperty("hostName");
        port = props.getProperty("port");
        intensity = props.getProperty("intensity");

       } 
    catch(Exception e){
        System.out.println("error" + e);
       }     
    }
     
    static public RFIDGetPropertyValues instance(){
        if (_instance == null) {
            _instance = new RFIDGetPropertyValues();
        }
        return _instance;
    }
}

Then anywhere in my code I was able to call

   RFIDGetPropertyValues dbInfo = RFIDGetPropertyValues.instance();
   String hostName = dbInfo.hostName; 
   String intensity = dbInfo.intensity;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM