0
点赞
收藏
分享

微信扫一扫

Springboot加载配置文件优先级以及类路径和项目路径区别

紫荆峰 2022-02-13 阅读 52

Spring官方文档地址:

   https://docs.spring.io/spring-boot/docs/2.1.3.RELEASE/reference/htmlsingle/#getting-started-first-application-pom

从官网可以看到Spring默认加载配置文件优先级为如下:

  1. 当前路径config
  2. 当前路径
  3. 类路径config
  4. 类路径

即前面的配置文件会覆盖后面的配置文件(当前路径指项目路径)

类路径(主要针对配置文件来讲)

   编译环境:就是resource下的路径,因为在项目编译后会自动将resources的文件放到target/class下面
    运行环境:指target/class
    jar包环境:一般是jar包中的\BOOT-INF\classes!

当前路径

编译环境和运行环境都指的是同一个路径,即当前项目的根路径,也就是项目名称所在的路径
jar包环境:jar包所在的当前路径.

注意:
@PropertySource注解 默认加载的路径是类路径.

获取类路径和当前项目路径的简单代码.
//获取当前类路径
File file = new File(SentinelApplication8401.class.getResource("/").getPath());
System.out.println(“类路径为:”+file);
//获取当前项目路径
File file1 = new File("");
try {
String canonicalPath = file1.getCanonicalPath();
System.out.println(“项目路径为:”+ canonicalPath);
} catch (IOException e) {
e.printStackTrace();
}

举报

相关推荐

0 条评论