在应用spring的工程中,使用class path的方式加载配置文件应该是最常用的做法,然而对大部分人来说,刚开始使用Spring时,几乎都碰到过加载配置文件失败的情况,除了配置上的错误外,很多时候是因为配置文件的路径和程序中指定的加载路径不一致,从而导致配置文件找不到,或是加载了错误地方的配置文件。本文将就Spring如何从class path中加载配置文件做一些简要的分析。
classpath:与classpath*:的区别在于,前者只会从第一个classpath中加载,而后者会从所有的classpath中加载
如果要加载的资源,不在当前ClassLoader的路径里,那么用classpath:前缀是找不到的,这种情况下就需要使用classpath*:前缀
另一种情况下,在多个classpath中存在同名资源,都需要加载,那么用classpath:只会加载第一个,这种情况下也需要用classpath*:前缀
可想而知,用classpath*:需要遍历所有的classpath,所以加载速度是很慢的,因此,在规划的时候,应该尽可能规划好资源文件所在的路径,尽量避免使用classpath*
情形一:使用classpath加载且不含通配符
这是最简单的情形,Spring默认会使用当前线程的ClassLoader的getResource
方法获取资源的
URL
,如果无法获得当前线程的
ClassLoader
,
Spring
将使用加载类
org.springframework.util.ClassUtils的ClassLoader。
1.当工程目录结构如图所示:
@H_404_92@ApplicationContext context =
new ClassPathXmlApplicationContext("conf/application-context.xml");来创建ApplicationContext对象的话,Spring将加载bin/conf目录下的application-context.xml文件。Spring启动时的输出显示为:
Loading XML bean definitions from
class path resource [conf/application-context.xml]
@H_404_92@