---
title: "使用spring中抽象的资源加载配置文件"
author: "robert.wei"
date: "2014-02-27T15:59:08Z"
tags: []
categories: ["开源软件"]
slug: "spring"
draft: false
lastmod: "2014-02-27T16:00:42Z"
id: 2023534
url: "https://robert-wei.iteye.com/blog/2023534"
---

熟悉spring的人都知道, spring把配置文件等抽象为了Resource，然后对Resource做了扩充，包括文件资源，网络资源等等。加载配置文件有时候由于打包等原因导致读取不到配置文件等问题经常遇到，现在使用spring的ResourceLoader来解决这块的问题。

1. 加载文件:
     使用FileSystemResourceLoader加载文件；
2. 加载classpath文件：
      使用ClassPathResourceLoader加载文件（包括打包之后在JAR包里的配置文件）；

但是这样很难记，spring做了路由， 直接使用DefaultResourceLoader就OK, 代码如下：
加载classpath下（包括jar包中的文件）

```java

    @Test
    public void testClassPathPropertyFile() throws IOException {
        String locationPattern = "classpath:ognl/wei.properties";
        ResourceLoader loader = new DefaultResourceLoader();
        Resource resource = loader.getResource(locationPattern);
        Properties prop = new Properties();
        prop.load(resource.getInputStream());
        for (Object key : prop.keySet()) {
            System.out.println("key:" + key + ", value:"
                    + prop.getProperty((String) key));
        }
    }

```


加载文件：只要把String locationPattern = "classpath:ognl/wei.properties";换成String locationPattern = "file:ognl/wei.properties";就正常了