Spring Bean裝配Resource的作用:方便的獲取項目所需要引入的文件資源
實現代碼
import java.io.IOException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
//實現ApplicationContextAware接口
public class MoocResource implements ApplicationContextAware{
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
this.applicationContext=arg0;
}
public void resource() throws IOException {
//獲取resource
//方法1. [ classpath:]可有可無
Resource resource = applicationContext.getResource("classpath:config.txt");
//方法2. 注意路徑中的分隔符爲“\\”或者“/”
//Resource resource = applicationContext.getResource("file:D:/Workspaces/test1\\resources\\config.txt");
//方法3.
//Resource resource = applicationContext.getResource("url:http://blog.csdn.net/qq_38325620/article/details/72654715");
System.out.println(resource.getFilename());
System.out.println(resource.contentLength());
}
}
輸出結果:
文件名稱
文件所佔內存的字節數