spring classpath路径和Resource类

时间:2022-12-22 16:34:53

spring classpath路径问题和Resource类的使用。

类文件:

package com.yb.t;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;

public class ClassA {

    // 持有一个Resource属性
    private Resource resource;

    public ClassA() {
        init();
    }

    private void init() {
        try {
            Resource r = new FileSystemResource("conf/test.txt");
            print(r.getInputStream(), "--------FileSystemResource");
            r = new ClassPathResource("conf/applicationContext-conf-test.xml");
            print(r.getInputStream(), "--------ClassPathResource");
            r = new PathResource("conf/test.txt");
            print(r.getInputStream(), "--------PathResource");
            r = new DefaultResourceLoader().getResource("classpath:conf/applicationContext-conf-test.xml");
            print(r.getInputStream(), "--------DefaultResourceLoader");
        } catch (IOException e) {
        }
    }

    public void printContent() {
        if (resource != null && resource.exists()) {
            try {
                print(resource.getInputStream(), "--------通过spring的xml配置文件读取resource");
            } catch (IOException e) {
            }
        }
    }

    public void print(InputStream inputStream, String desc) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            System.out.println(desc);
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (br != null) {
                br.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

}

spring配置文件:

<?xml version="1.0" encoding="UTF-8"?>   
<beans xmlns="http://www.springframework.org/schema/beans"   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"   
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
         http://www.springframework.org/schema/context   
         http://www.springframework.org/schema/context/spring-context-3.0.xsd">   
   
   <bean id="classA" class="com.yb.t.ClassA">  
      <property name="resource">  
         <value>file:conf/test.txt</value>  
      </property>  
   </bean>  
   
</beans>