spring classPath

Spring中使用classpath加载配置文件浅析

一曲冷凌霜 提交于 2019-12-01 15:10:10
在应用 Spring 的工程中,使用 class path 的方式加载配置文件应该是最常用的做法,然而对大部分人来说,刚开始使用 Spring 时,几乎都碰到过加载配置文件失败的情况,除了配置上的错误外,很多时候是因为配置文件的路径和程序中指定的加载路径不一致,从而导致配置文件找不到,或是加载了错误地方的配置文件。本文将就 Spring 如何从 class path 中加载配置文件做一些简要的分析。 情形一:使用 classpath 加载且不含通配符 这是最简单的情形, Spring 默认会使用当前线程的 ClassLoader 的 getResource 方法获取资源的 URL ,如果无法获得当前线程的 ClassLoader , Spring 将使用加载类 org.springframework.util.ClassUtils 的 ClassLoader 。 1. 当工程目录结构如图所示 : 即配置文件放在 bin 目录中的 conf 文件夹里,这时使用 ApplicationContext context = new ClassPathXmlApplicationContext("conf/application-context.xml"); 来创建 ApplicationContext 对象的话, Spring 将加载 bin/conf 目录下的 application