spring管理配置文件的工厂类--PropertiesFactoryBean

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

复制代码



classpath*:/conf/application.properties
classpath*:/conf/streamserver.properties


<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、结果:

发布了17 篇原创文章 · 获赞 2 · 访问量 2030

猜你喜欢

转载自blog.csdn.net/wumingdu1234/article/details/84540744