项目中读取配置文件的两种方式

 在项目中,我们往往会对我们的系统的配置信息进行统一管理,方便后期的修改和维护,将配置信息脱离出代码,到一个单独的配置文件。一般做法是将配置信息配置与一个cfg.properties的文件中,然后在我们系统初始化的时候,系统自动读取cfg.properties配置文件中的key value(键值对),然后对我们系统进行定制的初始化。
  那么一般情况下,我们使用的 java.util.Properties ,也就是java自带的。往往有一个问题是,每一次加载的时候,我们都需要手工的去读取这个配置文件,一来编码麻烦,二来代码不优雅,往往我们也会自己创建一个类来专门读取,并储存这些配置信息。
  Spring中提供着一个 PropertyPlaceholderConfigurer
  这个类是 BeanFactoryPostProcessor的子类。 (不懂自己度娘,可了解可不了解,下面我会讲大概)
其主要的原理在是。Spring容器初始化的时候,会读取xml或者annotation对Bean进行初始化。初始化的时候,这个PropertyPlaceholderConfigurer会拦截Bean的初始化,初始化的时候会对配置的${pname}进行替换,根据我们Properties中配置的进行替换。从而实现表达式的替换操作 。
    下面分别通过Java的Properties和Spring配置文件的方式介绍项目中通过配置文件管理参数

  • Java Properties
public class PropertiesUtil {

private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

private static Properties props;

static {
String fileName = "mmall.properties";
props = new Properties();
try {
props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName),"UTF-8"));
} catch (IOException e) {
logger.error("配置文件读取异常",e);
}
}

public static String getProperty(String key){
String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
return null;
}
return value.trim();
}

public static String getProperty(String key,String defaultValue){

String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
value = defaultValue;
}
return value.trim();
}
}

load ( InputStream inStream), 从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。
getProperty ( String key), 用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。



在Spring配置文件中
  1. 读取两个以上配置文件的方式  2.读取一个配置文件的方式
    <bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="order" value="2"/>
            <property name="ignoreUnresolvablePlaceholders" value="true"/>
             <property name="locations">
                    <list>
                            <value>classpath:datasource.properties</value>
                            <value>classpath:XXXXX.properties</value>
                    </list>
            </property>
            <property name="fileEncoding" value="utf-8"/>
    </bean>
    
    
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    
            <property name="location" value="classpath:cfg.properties"></property>
    
    </bean>

另外还有一种简单的配置方式
<!--采用这种方式简化配置文件--> 
<context:property-placeholder location="classpath:cfg.properties,classpath:cfg2.properties"/>

猜你喜欢

转载自blog.csdn.net/qq_28938627/article/details/80073145