springboot Running jar Package to Read External Configuration Files

  • 2021-11-02 01:04:26
  • OfStack

Case: This article mainly describes the linux system executes jar package to read the external configuration file of jar package sibling directory
Method 1: Relative path setting configuration file
(1) Create the configuration file conf. properties in the jar package sibling directory and write the configuration data:

confData=data

(2) Start writing automated test code


//from www.fhadmin.cn
public class Test{
    public String getData() throws IOException {
        // Read configuration file 
        Properties properties = new Properties();
        File file = new File("conf.properties");
        FileInputStream fis = new FileInputStream(file);
        properties.load(fis);
        fis.close();

        // Getting profile data 
        String confData = properties.getProperty("confData");
        System.out.println(confData);
    }
}

(3) Execute jar packets

java -jar jarNanexxx

Method 2: Absolute path setting configuration file
Solution: There is no problem when using the relative path method to manually execute jar package in the same level directory of jar package, but using crontab file of linux system to schedule and report errors regularly, because when we manually execute a script, it is carried out in the current shell environment, and the program can find environment variables; When the system automatically executes task scheduling, no other environment variables will be loaded except the default environment. Therefore, you need to specify all the environment variables required for the task to run in the crontab file, or use absolute paths in the program.
(1) Create the configuration file conf. properties in the jar package sibling directory and write the configuration data:

confData=data

(2) Start writing automated test code


//from www.fhadmin.cn
public class Test{
    public String getData() throws IOException {
       // Get jar Package sibling directory 
        String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        String[] pathSplit = path.split("/");
        String jarName = pathSplit[pathSplit.length - 1];
        String jarPath = path.replace(jarName, "");
        String pathName=jarPath+"minhang.properties";
        System.out.println(" Configuration file path: "+jarPath);

        // Read configuration file 
        Properties properties = new Properties();
        File file = new File(pathName);
        FileInputStream fis = new FileInputStream(file);
        properties.load(fis);
        fis.close();

        // Getting profile data 
        String confData = properties.getProperty("confData");
        System.out.println(confData);
    }
}

(3) Execute the jar packet

java -jar jarNanexxx


Related articles: