---
title: "Spring中关于classpath:和classpath*:前缀的一个小问题"
author: "hittyt"
date: "2012-06-29T13:44:11Z"
tags: []
categories: ["编程语言"]
slug: "spring-classpath-classpath"
draft: false
lastmod: "2012-06-29T13:44:11Z"
id: 1570936
url: "https://hittyt.iteye.com/blog/1570936"
---

在写Java代码时，有很多场景需要用到从classpath中加载资源。

使用Spring时，定义了比较方便的前缀风格告诉程序从哪里加载。

比较常用的有classpath:和classpath\*:两种前缀，用于指定从classpath中加载资源。但两者有些细微差别。

 

以加载Spring的配置文件为例，以下的写法大家应该比较熟悉：

 

```
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] {
                "classpath:META-INF/spring/a.bean.xml",
                 "classpath*:META-INF/spring/b.bean.xml" });
```

 

两种写法是希望在当前程序的classpath下去加载META-INF/spring/a.bean.xml和META-INF/spring/b.bean.xml。

但请注意，前者没有\*作为前缀，在classpath下面找不到META-INF/spring/a.bean.xml时，程序会马上抛出FileNotFoundException，提示你文件找不到，这种Fail Fast的风格，在定位问题的时候可能很有帮助。

后者因为加上了\*通配符，所以即使在classpath下面找不到META-INF/spring/b.bean.xml时，程序只会偷偷忍掉，不做任何错误提示。当然，这在某些特定的场景下，可能也是有意义的。

 

所以根据不同的使用场景，这两点区别可能需要注意一下。

另外，当某些时候，你怀疑Spring的某些配置文件加载的不对的时候，可以通过spring类库中提供的PathMatchingResourcePatternResolver类来来帮你定位一下，程序到底从哪里加载进来的你指定的配置文件，实例代码如下：

 

```
        try {
            for (Resource r : new PathMatchingResourcePatternResolver().getResources("your_locationPattern")){
                System.out.println("The real path is : "+r.getFile().getAbsolutePath());
            }
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
```