That thing about spring in the configuration file path

  In the project, we often need to read some configuration files for configuration information, but for the location of these configuration files are stored in the project as well as the storage path to obtain these profiles are often confused, their own research a little, recorded for future after use.

Test code as follows

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 under ( "/"). GetPath ()), to obtain a class path of the project file for compiled under springboot project resource directory will be placed in the classpath

  2, Main.class.getResource ( ""). GetPath (), acquired by the current class is the path where the packet Main.classs

  3, Main.class.getClassLoader (). GetResource ( ""). GetPath (), acquired by the class loader is the class path item

  4, can also use the spring of tools use ResourceUtils.getFile ( "classpath: application.properties") to get the configuration file in the resource directory

  5, finally jdk properties by means of the configuration file to read information

  Code results are as follows:

 

Guess you like

Origin www.cnblogs.com/hhhshct/p/11230049.html