Spring加载context配置文件是从classpath加载进来的。
What is classpath?
就是.java文件存放的根路径,在
intellij中是src目录我们也可以将配置文件单独放在一个文件夹下,例如
resources文件夹,该文件夹和src目录是同级的.怎么创建这个文件夹呢?
现在项目中创建一个和
src同级的directory,名为resources右键该
resources,然后make Directory As,然后选择Source Root此时你会发现该文件夹变颜色了,和src是一样的颜色
同时你也可以查看项目的配置问价
yourproject.xml,例如,我的是这样的:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="Spring" name="Spring">
<configuration />
</facet>
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/sources" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Spring-4.3.16.RELEASE" level="project" />
<orderEntry type="module-library">
<library name="JUnit4">
<CLASSES>
<root url="jar://$APPLICATION_HOME_DIR$/lib/junit-4.12.jar!/" />
<root url="jar://$APPLICATION_HOME_DIR$/lib/hamcrest-core-1.3.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</orderEntry>
</component>
</module>其中可以清楚的看到
src目录和sources都是sourceFolder
classpath*:和classpath:到底有什么区别呢?
你先想想*通常用来是干嘛用的? 是不是通配符?
- classpath*: 就是从多个jar文件,包括你自己的项目
src目录下(src目录作为sourceroot)加载指定的问价,比如:
1
2ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:/bean.xml");
// 其中斜杠表示sourceroot的根目录(也可以不写),它从所有的classpath中查找这个bean.xml文件,所有符合条件的bean.xml文件都被加载进来了
- classpath*: 就是从多个jar文件,包括你自己的项目
classpath: 如果存在多个满足条件的,第一个加载到了,就不管了
参考:
Spring加载resource时classpath*:与classpath:的区别
更多内容请点开上面的链接