eclipse的maven項目通過pom導入spring的支援,使用org.springframework.core.io.Resource去調用spring容器本身的資源,比如,讀取項目路徑下的某一個txt檔案的内容。
加載過程中報錯:

package com.springbootaware.aware.service;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
@Service
public class AwareService implements BeanNameAware, ResourceLoaderAware {
private String beanName;
private ResourceLoader loader;
@Override
public void setResourceLoader(ResourceLoader arg0) {
// TODO Auto-generated method stub
this.loader = arg0;
}
@Override
public void setBeanName(String arg0) {
// TODO Auto-generated method stub
this.beanName = arg0;
}
public void outputResult() {
System.out.println("bean的名字:" + beanName);
Resource r1 = loader.getResource("classpath:hosts.txt");
try {
System.out.println("ResourceLoader加載的檔案:" + IOUtils.toString(r1.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Resource r1 = loader.getResource("classpath:hosts.txt");
我們把hosts.txt檔案放在了src檔案夾下,這很顯然是錯誤的。
我們需要把被讀取的檔案放在.class檔案目錄結構中
然後運作代碼讀取txt檔案