zoukankan      html  css  js  c++  java
  • 关于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读取配置文件中的信息

      代码运行结果如下:

  • 相关阅读:
    flume和kafka整合(转)
    Flume目录
    Flume的安装配置
    HBase系统架构及数据结构(转)
    toolbar ,textfield,图片拉伸,Bundle
    poj 1017 Packets
    jQuery使用serialize(),serializeArray()方法取得表单数据+字符串和对象类型两种表单提交的方法
    Android数据加密概述及多种加密方式 聊天记录及账户加密 提供高质量的数据保护
    LintCode-落单的数 III
    LeetCode90:Subsets II
  • 原文地址:https://www.cnblogs.com/hhhshct/p/11230049.html
Copyright © 2011-2022 走看看