spring中resource是一個接口,為資源的抽象提供了一套操作方式,可匹配類似于classpath:XXX,file://XXX等不同協議的資源訪問。
如上圖所示,spring已經提供了多種訪問資源的實體類,還有DefaultResourceLoader類,使得與具體的context結合。在spring中根據設置的配置文件路徑轉換為對應的文件資源
// AbstractBeanDefinitionReader 文件
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
// DefaultResourceLoader 文件
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
for (ProtocolResolver protocolResolver : this.protocolResolvers) {
Resource resource = protocolResolver.resolve(location, this);
if (resource != null) {
return resource;
}
}
if (location.startsWith("/")) {
// ClassPathContextResource
return getResourceByPath(location);
}
else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
// 如果是以classpath:開頭,認為是classpath樣式的資源,返回ClassPathResource
}
else {
try {
URL url = new URL(location);
return new UrlResource(url);
// 符合URL協議,返回UrlResource
}
catch (MalformedURLException ex) {
return getResourceByPath(location);
// 剩下的無法判斷的全部返回ClassPathContextResource
}
}
}
// 然后在真正的使用resource的文件流時,XmlBeanDefinitionReader文件內
InputStream inputStream = encodedResource.getResource().getInputStream();
有多種具體的Resource類的獲取輸入流的實現方式。
FileSystemResource 類
public InputStream getInputStream() throws IOException {
return new FileInputStream(this.file);
// this.file 是個File對象
}
ClassPathContextResource和ClassPathResource的獲取IO流的方法是同一個
現在基本上清楚了spring針對不同協議的文件路徑是如何操作路徑,以什么樣子的方式獲取IO流,不過還是有幾個疑問需要深入了解下。
- 如何匹配多個資源文件
- FileSystemXmlApplicationContext和ClassPathXmlApplicationContext的區別
匹配多個資源文件
之前說的例子都是明確指定context.xml 的情況,可是現實中會配置多個配置文件,然后依次加載,例如*.xml會匹配當前目錄下面所有的.xml
文件。來到了PathMatchingResourcePatternResolver.class匹配出多個xml的情況
至于為什么會定位到PathMatchingResourcePatternResolver.class這個文件,可以看
AbstractApplicationContext 文件
public AbstractApplicationContext() {
this.resourcePatternResolver = getResourcePatternResolver();
}
protected ResourcePatternResolver getResourcePatternResolver() {
return new PathMatchingResourcePatternResolver(this);
}
// 也就意味著在context類初始化的時候,就直接設置了好了resourcePatternResolver對象為PathMatchingResourcePatternResolver
PathMatchingResourcePatternResolver 文件
public Resource[] getResources(String locationPattern) throws IOException {
Assert.notNull(locationPattern, "Location pattern must not be null");
if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) {
// 通過classpath:開頭的地址
if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) {
// 地址路徑中包含了 【*】這個匹配的關鍵字,意味著要模糊匹配
return findPathMatchingResources(locationPattern);
}
else {
// 查找當前所有的classpath資源并返回
return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()));
}
}
else {
// and on Tomcat only after the "*/" separator for its "war:" protocol.
int prefixEnd = (locationPattern.startsWith("war:") ? locationPattern.indexOf("*/") + 1 :
locationPattern.indexOf(":") + 1);
if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) {
// 除去前綴,包含【*】,進行模糊匹配
return findPathMatchingResources(locationPattern);
}
else {
// 這個是針對具體的xml文件的匹配規則,會進入到DefaultResourceLoader裝載資源文件
return new Resource[] {getResourceLoader().getResource(locationPattern)};
}
}
}
// 根據模糊地址找出所有匹配的資源文件
protected Resource[] findPathMatchingResources(String locationPattern) throws IOException {
String rootDirPath = determineRootDir(locationPattern);
// 根路徑,此處為xml/
String subPattern = locationPattern.substring(rootDirPath.length());
// 子路徑,此處為*.xml
Resource[] rootDirResources = getResources(rootDirPath);
// 調用本身,算出根路徑的資源信息
// 如果為xml/*.xml 則返回一個根路徑資源信息xml/
// 如果為xml/**/*.xml 則還是返回一組根路徑資源信息xml/
Set<Resource> result = new LinkedHashSet<Resource>(16);
for (Resource rootDirResource : rootDirResources) {
rootDirResource = resolveRootDirResource(rootDirResource);
URL rootDirURL = rootDirResource.getURL();
// 獲取其URL信息
if (equinoxResolveMethod != null) {
if (rootDirURL.getProtocol().startsWith("bundle")) {
rootDirURL = (URL) ReflectionUtils.invokeMethod(equinoxResolveMethod, null, rootDirURL);
rootDirResource = new UrlResource(rootDirURL);
}
}
if (rootDirURL.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
// jboss的文件協議
result.addAll(VfsResourceMatchingDelegate.findMatchingResources(rootDirURL, subPattern, getPathMatcher()));
}
else if (ResourceUtils.isJarURL(rootDirURL) ||
isJarResource(rootDirResource)) {
// jar包
result.addAll(doFindPathMatchingJarResources(rootDirResource, rootDirURL, subPattern));
}
else {
// 默認掃描當前的所有資源,添加到result中
result.addAll(doFindPathMatchingFileResources(rootDirResource, subPattern));
}
}
if (logger.isDebugEnabled()) {
logger.debug("Resolved location pattern [" + locationPattern + "] to resources " + result);
}
return result.toArray(new Resource[result.size()]);
}
// 通過路徑去匹配到合適的資源,此處的rootDir包含了絕對路徑
protected Set<File> retrieveMatchingFiles(File rootDir, String pattern)
throws IOException {
if (!rootDir.exists()) {
// 根路徑都不存在,則返回空
if (logger.isDebugEnabled()) {
logger.debug("Skipping [" + rootDir.getAbsolutePath() + "] because it does not exist");
}
return Collections.emptySet();
}
if (!rootDir.isDirectory()) {
// 不是文件夾,返回空
if (logger.isWarnEnabled()) {
logger.warn("Skipping [" + rootDir.getAbsolutePath() + "] because it does not denote a directory");
}
return Collections.emptySet();
}
if (!rootDir.canRead()) {
// 文件不可讀,也返回空
if (logger.isWarnEnabled()) {
logger.warn("Cannot search for matching files underneath directory [" + rootDir.getAbsolutePath() +
"] because the application is not allowed to read the directory");
}
return Collections.emptySet();
}
String fullPattern = StringUtils.replace(rootDir.getAbsolutePath(), File.separator, "/");
// 得到當前系統下的文件絕對地址
if (!pattern.startsWith("/")) {
fullPattern += "/";
}
fullPattern = fullPattern + StringUtils.replace(pattern, File.separator, "/");
// 得到完整的全路徑 例如/user/...*.xml
Set<File> result = new LinkedHashSet<File>(8);
doRetrieveMatchingFiles(fullPattern, rootDir, result);
// 得到當前rootDir下面的所有文件,然后配合fullPattern進行匹配,得到的結果在result中
return result;
}
protected void doRetrieveMatchingFiles(String fullPattern, File dir, Set<File> result) throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("Searching directory [" + dir.getAbsolutePath() +
"] for files matching pattern [" + fullPattern + "]");
}
File[] dirContents = dir.listFiles();
// 得到當前根路徑的所有文件(包含了文件夾)
if (dirContents == null) {
if (logger.isWarnEnabled()) {
logger.warn("Could not retrieve contents of directory [" + dir.getAbsolutePath() + "]");
}
return;
}
Arrays.sort(dirContents);
// 這個也需要注意到,這個順序決定了掃描文件的先后順序,也意味著bean加載的情況
for (File content : dirContents) {
String currPath = StringUtils.replace(content.getAbsolutePath(), File.separator, "/");
if (content.isDirectory() && getPathMatcher().matchStart(fullPattern, currPath + "/")) {
// 如果是文件夾,類似于xml/**/*.xml 文件
// 訪問到了** 就會是文件夾
if (!content.canRead()) {
...
}
else {
// 循環迭代訪問文件
doRetrieveMatchingFiles(fullPattern, content, result);
}
}
if (getPathMatcher().match(fullPattern, currPath)) {
result.add(content);
// 匹配完成,添加到結果集合中
}
}
}
這樣整個的xml文件讀取過程就全部完成,也清楚了實際中xml文件是什么樣的形式被訪問到的。
其實spring的路徑風格是和Apache Ant的路徑樣式一樣的,Ant的更多細節可以自行學習了解。
FileSystemXmlApplicationContext和ClassPathXmlApplicationContext的區別
這個看名字就很明顯,就是加載文件不太一樣,一個通過純粹的文件協議去訪問,另一個卻可以兼容多種協議。仔細分析他們的差異,會發現主要的差異就在于FileSystemXmlApplicationContext重寫的getResourceByPath方法
FileSystemXmlApplicationContext 文件
protected Resource getResourceByPath(String path) {
if (path != null && path.startsWith("/")) {
path = path.substring(1);
}
return new FileSystemResource(path);
}
上面代碼學習,已經清楚了在默認的中是生成ClassPathContextResource資源,但是重寫之后意味著被強制性的設置為了FileSystemResource,就會出現文件不存在的情況。
如下圖,設置的path只有context.xml
,就會被提示找不到文件,因為此時的文件路徑是項目路徑 + context.xml
如果改為使用simple-spring-demo/src/main/resources/context.xml
,此時需要注意修改xml內的properties文件路徑,否則也會提示文件找不到
這樣就符合設置了,運行正常,這也告訴我們一旦使用FileSystemXmlApplicationContext記得修改所有的路徑配置,以防止出現文件找不到的錯誤。