java读取配置文件的方法

来源:互联网 发布:淘宝哪家mcm高仿比较好 编辑:程序博客网 时间:2024/04/30 19:14

    java读取配置文件的方法

在编写java工程中,经常会用到配置文件,那如何读取配置文件呢,下面是两种常用的办法。

1.  使用Properties类,通过数据流来读取。

     2. 使用spring框架


     第一种,使用Properties类读取配置方法。

一般都会使用一个PropertiesUtil类来管理配置相关信息,比如:

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();    }}
具体调用:

Sring value = PropertiesUtil.getProperty("main.key");


第二种使用Spring的bean配置方式来读取配置文件。

配置参考文件如下:

<!-- 将多个配置文件读取到容器中,交给Spring管理 --><bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations"><list><value>classpath:global.properties</value><value>classpath:jdbc.properties</value><value>classpath:memcached.properties</value></list></property></bean>
1配置中使用,直接使用{mysql.host}这种方式来调用

2) 程序中使用,可以使用@value注解方式,比如:

@Value("#{search.auth_ip}")private String auth_ip ;