Spring中Resource(资源)的获取

本文介绍了Spring框架中资源加载的四种方式:通过Resource接口、ResourceLoader接口、ApplicationContext以及将resource注入到bean中。每种方式均有详细的讲解及示例代码。

Spring中获取资源的方式一共有以下四种:

  • 通过Resource接口获取资源
  • 通过ResourceLoader接口获取资源
  • 通过ApplicationContext获取资源
  • 将resource注入到bean中的方式获取资源

下面是对每种方式的详细讲解 :

1.通过Resource接口获取资源

Resource接口的实现类有:

实现类说明
ClassPathResource通过类路径获取资源文件
FileSystemResource通过文件系统获取资源
UrlResource通过URL地址获取资源
ByteArrayResource获取字节数组封装的资源
ServletContextResource获取ServletContext环境下的资源
InputStreamResource获取输入流封装的资源


Resource接口继承了InputStreamSource 接口,InputStreamSource 接口中有一个方法:getInputStream(),所以汇总起来,Resource接口中共有以下方法:

方法说明
exists()判断资源是否存在,true表示存在。
isReadable()判断资源的内容是否可读。需要注意的是当其结果为true的时候,其内容未必真的可读,但如果返回false,则其内容必定不可读。
isOpen()判断当前Resource代表的底层资源是否已经打开,如果返回true,则只能被读取一次然后关闭以避免资源泄露;该方法主要针对于InputStreamResource,实现类中只有它的返回结果为true,其他都为false。
getURL()返回当前资源对应的URL。如果当前资源不能解析为一个URL则会抛出异常。如ByteArrayResource就不能解析为一个URL。
getURI()返回当前资源对应的URI。如果当前资源不能解析为一个URI则会抛出异常。
getFile()返回当前资源对应的File。
contentLength()返回当前资源内容的长度。
lastModified()返回当前Resource代表的底层资源的最后修改时间。
createRelative()根据资源的相对路径创建新资源。[默认不支持创建相对路径资源]
getFilename()获取资源的文件名。
getDescription()返回当前资源底层资源的描述符,通常就是资源的全路径(实际文件名或实际URL地址)。
getInputStream()获取当前资源代表的输入流。除了InputStreamResource实现类以外,其它Resource实现类每次调用getInputStream()方法都将返回一个全新的InputStream。


演示代码:

public class ResourceTest {

    /**使用ClassPathResource获取资源**/
    @Test
    public void TestClassPath() throws IOException{
        Resource resource = new ClassPathResource("test.txt");

        //判断文件是否存在:
        if (resource.exists()) {
            System.out.println("文件存在");
        }

        //判断资源文件是否可读
        if (resource.isReadable()) {  
            System.out.println("文件可读"); 
        }

        //判断当前Resource代表的底层资源是否已经打开
        if (resource.isOpen()) {
            System.out.println("资源文件已打开");
        }

        System.out.println(resource.getURL());//获取资源所在的URL
        System.out.println(resource.getURI());//获取资源所在的URI
        resource.getFile();//返回当前资源对应的File。
        System.out.println(resource.contentLength());//输出内容长度
        System.out.println(resource.lastModified());//返回当前Resource代表的底层资源的最后修改时间。
        resource.createRelative("MyFile");//根据资源的相对路径创建新资源。[默认不支持创建相对路径资源]
        System.out.println(resource.getFilename());//获取资源文件名
        System.out.println(resource.getDescription());


        //获取当前资源代表的输入流
        if (resource.isReadable()) {
            InputStream is = resource.getInputStream();  
            System.out.println(is);
            is.close();
        }

    }

    /**使用FileSystemResource获取资源**/
    @Test
    public void TestFileSystem() throws IOException {
        Resource resource = new FileSystemResource("D:\\test.txt");
        System.out.println(resource.getFilename());
    }

    /**使用UrlResource获取资源**/
    @Test
    public void TestUrl() throws MalformedURLException{
        Resource resource = new UrlResource("http://docs.spring.io/spring/docs/4.0.0.M1/spring-framework-reference/pdf/spring-framework-reference.pdf");
        System.out.println(resource.getFilename());
    }

    /**使用ByteArrayResource获取字节数组封装的资源**/
    @Test
    public void testByteArray() throws IOException {
        ByteArrayResource resource = new ByteArrayResource("Hello".getBytes()); 
        System.out.println(resource.getInputStream());

    }


    /**使用InputStreamResource获取输入流封装的资源。针对于输入流的Resource,其getInputStream()方法只能被调用一次。**/  
       @Test  
       public void testInputStream() throws Exception {  
          InputStream is = new FileInputStream("D\\test.txt");  
          InputStreamResource resource = new InputStreamResource(is);  
          //对于InputStreamResource而言,其getInputStream()方法只能调用一次,继续调用将抛出异常。  
          InputStream is2 = resource.getInputStream();   //返回的就是构件时的那个InputStream
          System.out.println(is2);
          is.close();
       } 

}

2.通过ResourceLoader接口获取资源

Spring框架为了更方便的获取资源,尽量弱化程序员对各个Resource接口的实现类的感知,定义了另一个ResourceLoader接口。该接口的getResource(String location)方法可以用来获取资源。它的DefaultResourceLoader实现类可以适用于所有的环境,可以返回ClassPathResource、UrlResource等。

ResourceLoader在进行加载资源时需要使用前缀来指定需要加载:“classpath:path”表示返回ClasspathResource,“http://path”和“file:path”表示返回UrlResource资源,如果不加前缀则需要根据当前上下文来决定,DefaultResourceLoader默认实现是加载classpath资源。
示例代码:

       @Test  
       public void testResourceLoader() { 

              ResourceLoader loader = new DefaultResourceLoader();  
              Resource resource = loader.getResource("http://www.baidu.com");  
              System.out.println(resource instanceof UrlResource); //true  
              resource = loader.getResource("classpath:test.txt");  
              System.out.println(resource instanceof ClassPathResource); //true  
              resource = loader.getResource("test.txt");  
              System.out.println(resource instanceof ClassPathResource); //true  

       } 

3.通过ApplicationContext获取资源

事实上,所有ApplicationContext实例都实现了ResourceLoader接口,因此我们在使用Spring容器时,可以不去过于计较底层Resource的实现,也不需要自己创建Resource实现类,而是直接使用applicationContext.getResource(),获取到bean容器本身的Resource,进而取到相关的资源信息。
示例代码:
首先创建一个MyResource类:这个类实现了ApplicationContextAware接口来获取上下文对象

public class MyResource implements ApplicationContextAware {
        private ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void resource() throws IOException {
        Resource resource = applicationContext.getResource("file:D:\\test.txt");
        System.out.println(resource.getFilename());
        System.out.println(resource.contentLength());

    }

}

配置xml文件:

<bean id="myResource" class="com.spring.test.MyResource"></bean>

测试类:

public class App {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-resource.xml");  
        MyResource myResource = (MyResource) context.getBean("myResource");
        try {
            myResource.resource();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

测试结果:这里写图片描述

4.将resource注入到bean中的方式获取资源

通过依赖注入的方式把Resource注入到bean中。
示例代码:

public class MyResource {
    private Resource resource;

    public void setResource(Resource resource) {
        this.resource = resource;
    }

    public void resource() throws IOException {
        System.out.println(resource.getFilename());
        System.out.println(resource.contentLength());
    }

}

配置spring-resource xml文件:

<bean id="myResource" class="com.spring.test.MyResource">
        <property name="resource">
            <value>classpath:test.txt</value>
        </property>
    </bean>

测试类:

public class App {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-resource.xml");  
        MyResource myResource = (MyResource) context.getBean("myResource");
        try {
            myResource.resource();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

测试结果为:这里写图片描述

参考资料:http://elim.iteye.com/blog/2016305

<think>我们正在讨论Spring Boot中获取国际化资源文件的方法。根据引用[2],Spring Boot通过MessageSourceProperties和ResourceBundleMessageSource来管理国际化资源。用户想要知道如何使用Resource对象来获取这些国际化资源文件(可能是直接获取文件内容或路径)。 引用[3]提供了四种获取resource文件夹下资源文件的方法,我们可以参考这些方法来获取国际化资源文件。国际化资源文件通常位于classpath下,如`messages.properties`、`messages_en.properties`等。 注意:国际化资源文件一般通过MessageSource来访问,而不是直接读取文件。但用户明确要求使用Resource获取,所以我们将展示如何通过Resource对象获取国际化资源文件的内容。 步骤: 1. 确定国际化资源文件的位置,默认在classpath根目录下,但也可以在`spring.messages.basename`中配置(例如:`classpath:i18n/messages`)。 2. 使用SpringResourceLoader或者通过ClassPathResource来加载资源文件。 示例代码: 假设我们的国际化资源文件名为`messages.properties`,位于`src/main/resources`目录下(即classpath根目录)。 我们可以使用以下方法之一: 方法一:使用ClassPathResource ```java import org.springframework.core.io.ClassPathResource; import org.springframework.util.FileCopyUtils; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; // ... // 指定资源路径,注意:路径不需要前缀classpath:,直接从classpath根目录开始 ClassPathResource resource = new ClassPathResource("messages.properties"); try { String content = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)); System.out.println(content); } catch (IOException e) { e.printStackTrace(); } ``` 方法二:使用ResourceLoader(推荐在Spring Bean中使用) 在Spring管理的Bean中,可以注入ResourceLoader,然后使用它来加载资源。 ```java import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Component; import org.springframework.util.FileCopyUtils; import javax.annotation.PostConstruct; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; @Component public class MyComponent { private final ResourceLoader resourceLoader; public MyComponent(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @PostConstruct public void init() { // 加载资源文件,路径可以是classpath:开头 Resource resource = resourceLoader.getResource("classpath:messages.properties"); try { String content = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)); System.out.println(content); } catch (IOException e) { e.printStackTrace(); } } } ``` 注意:国际化资源文件可能有多个(如不同语言),我们需要根据实际文件名来加载。例如,要加载英文资源文件,可以指定文件名为`messages_en.properties`。 但是,直接读取国际化资源文件并不是常见的做法,因为Spring Boot已经通过MessageSource为我们提供了国际化的支持。通常,我们使用MessageSource来获取国际化的消息。 例如,使用MessageSource的方式: ```java @Autowired private MessageSource messageSource; public String getMessage(String code, Object[] args, Locale locale) { return messageSource.getMessage(code, args, locale); } ``` 但是,用户要求使用Resource获取,所以我们提供了上述直接读取文件的方法。 另外,引用[3]中提到的第三种方法(使用ClassLoader获取输入流)也可以使用: ```java InputStream inputStream = getClass().getClassLoader().getResourceAsStream("messages.properties"); // 然后读取输入流 ``` 不过请注意,如果文件在jar包内,使用getFile()方法可能会抛出FileNotFoundException,因为jar包内的资源不是一个文件系统路径。因此,推荐使用getInputStream()来读取内容。 总结:在Spring Boot中,可以通过ClassPathResourceResourceLoader或ClassLoader来获取国际化资源文件的内容,但要注意文件路径和读取方式(避免使用getFile(),而使用流)。 相关问题: 1. Spring Boot中如何配置多个国际化资源文件? 2. 如何在非Spring管理的类中获取国际化资源文件? 3. 使用Resource读取资源文件时,如何处理不同环境下的路径问题? </think>在 Spring Boot 中通过 `Resource` 获取国际化资源文件的方法如下,结合引用[2]的国际化和引用[3]的资源加载技术: ### 一、核心方法(推荐) #### 1. **使用 `ResourceLoader` 注入(推荐)** ```java @Autowired private ResourceLoader resourceLoader; public Resource getI18nResource(String filename, Locale locale) { // 示例路径: i18n/messages_zh_CN.properties String path = "classpath:i18n/" + filename + "_" + locale + ".properties"; return resourceLoader.getResource(path); } ``` #### 2. **使用 `ClassPathResource`** ```java Resource resource = new ClassPathResource("i18n/messages_en_US.properties"); try (InputStream inputStream = resource.getInputStream()) { // 处理文件流 } catch (IOException e) { e.printStackTrace(); } ``` --- ### 二、关键注意事项 1. **文件位置** 国际化文件需放在 `src/main/resources` 下,例如: ``` resources/ ├── i18n/ │ ├── messages.properties # 默认 │ ├── messages_zh_CN.properties │ └── messages_en_US.properties ``` 2. **路径规范** - 路径需与 `spring.messages.basename` 配置匹配(默认 `messages`)[^2] - 文件名格式:`{basename}_{language}_{region}.properties` 3. **读取文件内容** 使用 Spring 工具类简化操作: ```java String content = StreamUtils.copyToString( resource.getInputStream(), StandardCharsets.UTF_8 ); ``` --- ### 三、对比方案 | 方法 | 优点 | 缺点 | |----------------------|------------------------------|-------------------------------| | `ResourceLoader` | 支持动态路径,灵活度高 | 需依赖注入 | | `ClassPathResource` | 无需注入,适合工具类 | 路径硬编码 | | `ClassLoader` | 兼容旧版 Spring | 需手动处理编解码[^3] | --- ### 四、完整示例 ```java @Service public class I18nService { @Autowired private ResourceLoader resourceLoader; public Properties loadMessages(Locale locale) throws IOException { Resource resource = resourceLoader.getResource( "classpath:i18n/messages_" + locale.toLanguageTag() + ".properties" ); Properties props = new Properties(); try (InputStream is = resource.getInputStream()) { props.load(new InputStreamReader(is, StandardCharsets.UTF_8)); } return props; } } ``` > **注意**:生产环境建议使用 Spring 内置的 `MessageSource` 接口(引用[2]),而非直接操作资源文件: > ```java > @Autowired private MessageSource messageSource; > String msg = messageSource.getMessage("hello", null, locale); > ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值