您的位置:首页 > 运维架构

读取属性配置文件

2014-10-30 11:09 435 查看
读取properties配置文件

一:利用java.util.Properties读取

package com.ailk.common.utils;

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

/**

 * 配置文件

 * Title: mail-box <br>

 * Description: <br>

 * Date: 2013-6-4 <br>

 * Copyright (c) 2013 AILK <br>

 *

 * @author supeng

 */

public class PropertiesUtil {

    private static Properties props = null;

//    private transient static Log log = LogFactory.getLog(PropertiesUtil.class);

    

    /**

     * 根据文件名读取配置文件

     * @param fileName

     * @return

     * @throws Exception

     * @author supeng

     */

    public static Properties getProperties(String fileName) {

         Properties props = new Properties();

        try {

            InputStream inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);

            props.load(inputStream);

        } catch (IOException e) {

            e.printStackTrace();

        }

        return props;

    }

    

    synchronized public static String getConfiguration(String properties,String configName){

        try {

            props = PropertiesUtil.getProperties(properties);

        } catch (Exception e) {

            e.printStackTrace();

//            log.error(e);

        }

        return props.getProperty(configName);

    }

    

    public static void main(String[] args) {

        Properties p = PropertiesUtil.getProperties("ssoservice.properties");

        System.out.println(p.getProperty("sso.socket.timeout"));

    }

}

二:利用spring读取properties 文件

利用org.springframework.beans.factory.support.PropertiesBeanDefinitionReader来读取属性文件 //bean节点配置的class类

  BeanDefinitionRegistry reg = new DefaultListableBeanFactory();

  PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(reg);

  reader.loadBeanDefinitions(new ClassPathResource("beanConfig.properties"));

  BeanFactory factory = (BeanFactory)reg;

  HelloBean helloBean =(HelloBean)factory.getBean("helloBean");

 System.out.println(helloBean.getHelloWorld());
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  properties