1. 程式人生 > >載入檔案的幾種方式

載入檔案的幾種方式

一、通過檔案路徑載入

InputStream ips = new FileInputStream("config.properties");

二、直接通過getResourceAsStream進行載入    

//配置檔案需要放在當前包目錄下
		InputStream ips = ReflectCollection.class
			.getResourceAsStream("resources/config.properties");

這種方式也可以使用絕對路徑,絕對路徑需要加上斜槓(/)。不管是絕對還是相對路徑,底層呼叫都是類載入器。

//絕對路徑的方式
		InputStream ips = ReflectCollection.class
				.getResourceAsStream(
		"/cn/sunft/day01/reflect/resources/config.properties");

三、通過類載入的方式進行載入

在classpath所在的根目錄下查詢檔案,檔案需要直接放在classpath指定的目錄下,另外目錄最前面不要加斜槓(/)。

//在classpath所在的根目錄下查詢檔案
		//注意這裡的檔案需要直接放在classpath指定的目錄下,
		//另外目錄最前面不要加/,通過這種方式檔案通常不需要修改
		InputStream ips = ReflectCollection.class
				.getClassLoader()
		.getResourceAsStream("cn/sunft/day01/reflect/config.properties")

四、Spring載入Properties配置檔案

一、通過 context:property-placeholder 標籤實現配置檔案載入

<context:property-placeholder ignore-unresolvable="true" location="classpath:redis-key.properties"/>

2、在 spring.xml 中使用配置檔案屬性:

        <!-- 基本屬性 url、user、password -->
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />

3、在java檔案中使用:     

  @Value("${jdbc_url}")  
            private  String jdbcUrl; // 注意:這裡變數不能定義成static 

二、通過 util:properties 標籤實現配置檔案載入
1、用法示例: 在spring.xml配置檔案中新增標籤

<util:properties id="util_Spring"  local-override="true" location="classpath:jeesite.properties"/>

2、在spring.xml 中使用配置檔案屬性:

<property name="username" value="#{util_Spring['jdbc.username']}" />
    <property name="password" value="#{util_Spring['jdbc.password']}" />

3、在java檔案中使用:

@Value(value="#{util_Spring['UTIL_SERVICE_ONE']}")
    private String UTIL_SERVICE_ONE;

三、通過 @PropertySource 註解實現配置檔案載入
1、用法示例:在java類檔案中使用 PropertySource 註解:

@PropertySource(value={"classpath:redis-key.properties"})
public class ReadProperties {
@Value(value="${jdbc.username}")
 private String USER_NAME;
}

2、在java檔案中使用:

@Value(value="${jdbc.username}")
 private String USER_NAME;


四、通過 PropertyPlaceholderConfigurer 類讀取配置檔案

1、用法示例:在 spring.xml 中使用 <bean>標籤進行配置

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:redis-key.properties</value>
            </list>
        </property>
      </bean>


2、 PropertyPlaceholderConfigurer 配置方法,等價於 方式一,用法參考方法一。

        <!-- 基本屬性 url、user、password -->
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />