spring管理配置文件的工廠類--PropertiesFactoryBean


使用這個工廠的配置,可以很方便的獲取配置文件中的屬性。具體使用如下;

對於屬性配置,一般采用的是鍵值對的形式,如:
key=value
屬性配置文件一般使用的是XXX.properties,當然有時候為了避免eclipse把properties文件轉碼,放到服務器上認不出中文,可以采用XXX.conf的形式管理屬性配置。
spring對於屬性文件有自己的管理方式,通過spring的管理,可以直接使用@Value的方式直接得到屬性值。
先使用org.springframework.beans.factory.config.PropertiesFactoryBean對屬性配置文件進行管理。

1.新建一個Java project,命名spring_test;

2.導入jar包:

aopalliance-1.0.jar  
commons-logging-1.1.1.jar  
org.springframework.test-3.1.0.RELEASE.jar  
spring-aop-3.1.1.RELEASE.jar  
spring-asm-3.1.1.RELEASE.jar  
spring-beans-3.1.1.RELEASE.jar  
spring-context-3.1.1.RELEASE.jar  
spring-context-support-3.1.1.RELEASE.jar  
spring-core-3.1.1.RELEASE.jar  
spring-expression-3.1.1.RELEASE.jar 

3、在resources下建立conf目錄,並且conf目錄下建立Application.properties

4、根據業務寫相關配置:

state=1
server.ip=10.10.33.174
server.port=50001

5、新建一個對象來獲取配置屬性

package com.atomview.signalgateway.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Created on 2017/6/9.
 */

public class StreamServerProperties {

    @Value("#{propertiesReader['state']}")
    private String m_ConnectState;

    @Value("#{propertiesReader['server.ip']}")
    private String m_StreamserverIp;

    @Value("#{propertiesReader['server.port']}")
    private String m_StreamserverPort;

    public String getConnectState() {
        return m_ConnectState;
    }

    public String getStreamserverIp() {
        return m_StreamserverIp;
    }

    public String getStreamserverPort() {
        return m_StreamserverPort;
    }
}

6、配置一下配置文件的工廠bean

   <bean id="propertiesReader"
          class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath*:/conf/application.properties</value>
                <value>classpath*:/conf/streamserver.properties</value>
            </list>
        </property>
    </bean>
    
    <bean id="serverproperties" class="com.atomview.signalgateway.config.StreamServerProperties"/>

7、測試類:

    public static ApplicationContext getContext(){
        ApplicationContext context = new FileSystemXmlApplicationContext("classpath:spring_framework.xml");
        return context;
    }
    public static void main(String[] args){
        ApplicationContext context = getContext();
        StreamServerProperties tProperties = (StreamServerProperties) context.getBean("serverproperties");
        System.out.println(tProperties.getStreamserverIp());
    }

8、結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM