Home >Java >javaTutorial >How does springboot run the jar package to read external configuration files?
Method 1: Set the configuration file with a relative path
(1) Create the configuration file conf.properties in the same directory as the jar package and write the configuration data:
confData=data
(2) Start writing the automated test code
//from www.fhadmin.cn public class Test{ public String getData() throws IOException { //读取配置文件 Properties properties = new Properties(); File file = new File("conf.properties"); FileInputStream fis = new FileInputStream(file); properties.load(fis); fis.close(); //获取配置文件数据 String confData = properties.getProperty("confData"); System.out.println(confData); } }
(3) Execute the jar package
java -jar jarNanexxx
Method 2: Absolute path setting configuration file
Solution to the problem: There is no problem when using the relative path method to manually execute the jar package in the same level directory of the jar package, but an error occurs when using the crontab file of the Linux system for scheduled scheduling. The reason is: Because when we manually execute a script, we do it in the current shell environment, and the program can find the environment variables; and when the system automatically performs task scheduling, it will not load any other environment variables except the default environment. Therefore, you need to specify all the environment variables required for task running in the crontab file, or use absolute paths in the program.
(1) Create the configuration file conf.properties in the same directory as the jar package and write the configuration data:
confData=data
(2) Start writing Enter the automated test code
//from www.fhadmin.cn public class Test{ public String getData() throws IOException { //获取jar包同级目录 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("配置文件路径:"+jarPath); //读取配置文件 Properties properties = new Properties(); File file = new File(pathName); FileInputStream fis = new FileInputStream(file); properties.load(fis); fis.close(); //获取配置文件数据 String confData = properties.getProperty("confData"); System.out.println(confData); } }
(3) Execute the jar package
java -jar jarNanexxx
The above is the detailed content of How does springboot run the jar package to read external configuration files?. For more information, please follow other related articles on the PHP Chinese website!