spring classpath路徑和Resource類

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>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章