1. 介绍
Java本身提供了对资源文件访问的接口,Spring对于资源加载也有着一套自己的框架,相比之下会更加方便。Spring 提供的所有接口都继承Resource。经常使用的:
- FileSystemResource
文件系统资源,资源一文件系统的路径表示,如D:/aaa/vvv.java。类似于Java中的File。 - PathResource
Spring4.0提供的读取资源文件的新类。Path封装了java.net.URL、java.nio.Path、文件系统资源,它使用户能够访问任何可以通过URL、Path、系统文件路径表示的资源,如文件系统的资源,HTTP资源、FTP资源等。 - ClassPathResource
类路径下的资源,资源以相对路径的方式表示,类似于this.getClass().getResource("/").getPath(); - ServletContextResource
访问Web容器上下文中的资源而设计的类,负责对于Web应用根目录的路径加载资源。它支持以流和URL的方式访问,在WAR解包的情况下,也可以通过File方式访问。该类还可以直接从JAR包中访问资源。类似于request.getServletContext().getRealPath("");
2. 常见的用法
(1)读取配置文件ClassPathResource
private static Properties THIRD_PROPS;
THIRD_PROPS = PropertiesLoaderUtils.loadProperties(new EncodedResource(
new ClassPathResource(ThirdConstants.THIRD_CONFIG_PATH_LOCAL), ThirdConstants.DEFAULT_CHART
));
(2)读取xml配置文件FileSystemResource
Resource rs = new FileSystemResource("D:/software/tomcat/webapps/springWebDemo/WEB-INF/classes/beanConfig.xml");
BeanFactory factory = new XmlBeanFactory(rs);
HelloBean helloBean = (HelloBean)factory.getBean("helloBean");
System.out.println(helloBean.getHelloWorld());
//补充另外一种方法
ApplicationContext context = new ClassPathXmlApplicationContext("beanConfig.xml");
HelloBean helloBean = (HelloBean)context.getBean("helloBean");
System.out.println(helloBean.getHelloWorld());
3.知识拓展
(1)关于路径,不同平台路径的写法不一样,如:
- 在java中路径一般用"/"
- windows中的路径一般用""
- linux、unix中的路径一般用"/"
主要有两种,反斜杠在配置文件路径时,由于它本身在java中有特殊意义,作为转义符而存在,所以具体意义上的反斜杠要两个。如:
String path="D:\\新建文件夹\\2.png";
File file=new File(path);
System.out.println(file.exists());
String path1="D:/新建文件夹/2.png";
File file1=new File(path);
System.out.println(file1.getAbsolutePath());
System.out.println(file1.getCanonicalPath());
上面两种都可以达到访问路径的效果。目前windows下也能识别“/”,所以最好用“/”,这样都能统一。
(2)File.separator
file.separator这个代表系统目录中的间隔符,说白了就是斜线,不过有时候需要双线,有时候是单线,你用这个静态变量就解决平台路径兼容问题了。
网友评论