读取配置信息方式

一般项目中都有读取配置信息的基本要求。下面记录一些实用的方法。

1. 使用工具类propertiesUtil

package com.lingnanpass.common.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

/**
 * Properties属性集合,读取项目根路径下的config.properties文件
 * 创建时间:2016年11月17日 下午2:45:06
 */
public class PropertiesUtil {
    private static Logger logger = LogManager.getLogger(PropertiesUtil.class);
     //属性文件的路径   
    static String profile="config.properties";   
    private static Properties props = new Properties();   

    static {   
        try {   
            props.load(PropertiesUtil.class.getResourceAsStream("/"+profile));   
        } catch (FileNotFoundException e) {   
            e.printStackTrace();   
            logger.error(profile+" is not found:"+e.getMessage());  
        } catch (IOException e) {          
            logger.error(profile+" I/O exception:"+e.getMessage());  
        }   
    }   

   /**
    * 获取prop的制定key的值 
    * @param key 
    * @return
    */
    public static String get(String key) {   
        return props.getProperty(key);   
    }   


    /**
     * 插入一对prop   
     * @param key
     * @param name
     */
    public static void set(String key,String value) {          
        props.setProperty(key, value);
    }   
}

2. 通过注解@Value读取配置

第一步:
首先spring的applicationContext.xml文件引入配置文件

<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath:jdbc.properties</value>
            </list>
        </property>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="properties" ref="configProperties"></property>
</bean>

第二步:
配置jdbc.properties文件

jdbc.initialPoolSize =2
jdbc.maxWaitTime =60000
jdbc.checkIdlePoolTime = 60000
jdbc.minConnTime = 300000
name=nihao

第三步:

通过注解@Value获取配置信息

@Value("#{configProperties['name']}")
private String name;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值