java读取properties配置文件

来源:互联网 发布:为什么手机网络不稳定 编辑:程序博客网 时间:2024/05/19 02:03
对于一些公用常量,放到properties文件中方便统一管理。而Java语言读取properties资源文件又有多种实现方式,流、注解等方式。下面简述两种常用的方式。

方式一、通过spring的注解@Value实现(版本Spring 3.0+):
@Value("${address}")
private String address;

对应application.properties文件中的address,就可以成功的给address属性赋值
address=192.168.10.156

以上方式一中,是建立在springboot框架中,可以默认读取到application.properties文件;若key不在默认的application.properties文件中,则需在启动类中添加配置文件:
@PropertySource({"classpath:application.properties"})

若需要加载多个,逗号分隔:
@PropertySource({"classpath:application.properties","constants.properties",……})

若在普通的spring项目中,则需在配置文件中添加如下配置:
<context:property-placeholderlocation="classpath:spring.properties"/>或者:

<bean id="propertyBean"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location">
    <value>classpath:*.properties</value>
  </property>
</bean>

方式二、类中通过ResourceBundle读取资源文件:
ResourceBundle resourceBundle = ResourceBundle.getBundle("spring-context");
resourceBundle.getString("address");

这样也可以读到spring-context资源文件中的address对应的值。