关于spring中配置文件路径的那些事儿

  在项目中我们经常会需要读一些配置文件来获取配置信息,然而对于这些配置文件在项目中存放的位置以及获取这些配置文件的存放路径却经常搞不清楚,自己研究了一下,记录下来以备后用。

测试代码如下

package com.example.test.aspect;

import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

public class Main {

    public static void main(String[] args) throws Exception{
        System.out.println(Main.class.getResource("/application.properties").getPath());
        System.out.println(Main.class.getResource("").getPath());
        System.out.println(Main.class.getClassLoader().getResource("").getPath());
        System.out.println(ResourceUtils.getFile("classpath:application.properties"));

        File file = new File(Main.class.getClassLoader().getResource("application.properties").getPath());
        InputStream inputStream = new FileInputStream(file);
        Properties properties = new Properties();
        properties.load(inputStream);
        System.out.println(properties.getProperty("sdf"));

    }


}

  1、Main.class.getResource("/").getPath()) , 获取的是项目的类路径,对于springboot项目resource目录下的文件编译后会放在类路径下

  2、Main.class.getResource("").getPath(),获取的则是当前类Main.classs所在包的路径

  3、Main.class.getClassLoader().getResource("").getPath(),通过类加载器获取的是项目的类路径

  4、还可以使用spring的工具类利用ResourceUtils.getFile("classpath:application.properties")获取resource目录下的配置文件

  5、最后借助于jdk properties读取配置文件中的信息

  代码运行结果如下:

猜你喜欢

转载自www.cnblogs.com/hhhshct/p/11230049.html