加載文件的幾種方式

1、經過文件路徑加載

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

2、直接經過getResourceAsStream進行加載    

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

這種方式也能夠使用絕對路徑,絕對路徑須要加上斜槓(/)。無論是絕對仍是相對路徑,底層調用都是類加載器。java

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

3、經過類加載的方式進行加載

在classpath所在的根目錄下查找文件,文件須要直接放在classpath指定的目錄下,另外目錄最前面不要加斜槓(/)。redis

//在classpath所在的根目錄下查找文件
		//注意這裏的文件須要直接放在classpath指定的目錄下,
		//另外目錄最前面不要加/,經過這種方式文件一般不須要修改
		InputStream ips = ReflectCollection.class
				.getClassLoader()
		.getResourceAsStream("cn/sunft/day01/reflect/config.properties")

4、Spring加載Properties配置文件

1、經過 context:property-placeholder 標籤實現配置文件加載spring

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

二、在 spring.xml 中使用配置文件屬性:ide

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

三、在java文件中使用:     url

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

2、經過 util:properties 標籤實現配置文件加載
一、用法示例: 在spring.xml配置文件中添加標籤spa

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

二、在spring.xml 中使用配置文件屬性:code

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

三、在java文件中使用:xml

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

3、經過 @PropertySource 註解實現配置文件加載
一、用法示例:在java類文件中使用 PropertySource 註解:ip

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

二、在java文件中使用:get

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


4、經過 PropertyPlaceholderConfigurer 類讀取配置文件

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

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


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

        <!-- 基本屬性 url、user、password -->
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
相關文章
相關標籤/搜索