properties配置文件的读取

简介: properties配置文件的读取

现在的项目为了更易维护,一般都是使用配置文件。这样做更灵活,可以很方便应对不同的环境。properties文件大家也见得多了,下面介绍一下properties的读取问题

一、普通类加载:

public FileSkServer() {
    Properties pro = new Properties();
    pro.load(FileSkServer.class.getResourceAsStream("configure.properties"));//在跟类同一个目录里面的文件
    String port = pro.getProperty("fileServer.port");//配置文件里的字段
}

使用pro.getProperty("fileServer.port");就可以获取fileServer.port的值了

二、spring MVC Controller加载方式:

1、首先在applicationContext.xml配置

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

configure.properties是你的文件名,config是配置文件所在的目录,

结构

然后在Controller里中使用注解获得配置项内容:

@Value("#{configProperties['server.file.path']}")
  private String filePath;
  public void setFilePath(String filePath) {
    this.filePath = filePath;
  }

这样就可以直接获取配置项server.file.path了


------------------------------------20160510添加------------------------------------

三、通过ResourceBundle来加载

示例代码:

ResourceBundle bundle=ResourceBundle.getBundle("config");
String driver=bundle.getString("driver");


创建一个默认的ResourceBundle对象  

ResourceBundle会查找WEB-INF\classes\下的config.properties的文件  

它跟普通java类的命名规则完全一样:  

- 区分大小写  

- 扩展名 .properties 省略。就像对于类可以省略掉 .class扩展名一样  

- 资源文件必须位于指定包的路径之下(位于所指定的classpath中)  

假如你是在非Web项目中使用,则一定要写资源文件的路径,也就是包路径必须存在。

如果是Web项目,不写包路径可以,此时将资源文件放在WEB-INF\classes\目录下就可以。

然后可以直接获取值,这里也是区分大小写的,大家注意


--------------------------------------20170626添加--------------------------------------

四、通过spring框架来读取

try {
  config = PropertiesLoaderUtils.loadProperties(new EncodedResource(new ClassPathResource("configure.properties"), Consts.UTF_8));
} catch (Exception e) {
  e.printStackTrace();
}

查找WEB-INF\classes\下的config.properties的文件,也可以放到其他目录。

相关文章
|
2月前
|
存储 自然语言处理 Java
ResourceBundle.getBundle()来读取自定义的properties配置文件
ResourceBundle.getBundle()来读取自定义的properties配置文件
63 1
|
XML 移动开发 Java
log4j.properties配置文件详解
log4j.properties配置文件详解
535 0
|
8月前
|
Java
Properties文件操作
Properties文件操作
37 0
解决使用Properties读取中文乱码问题
解决使用Properties读取中文乱码问题
598 0
|
数据格式
如何优雅的读取yml配置文件?
如何优雅的读取yml配置文件?
175 0
|
安全 Java Spring
实战小技巧14:配置文件Properties
properties配置文件,相信各位小伙伴都不会太陌生,常用Spring的可能会经常看到它,虽说现在更推荐的是使用Yaml配置文件,但是properties配置文件的使用频率也不低 在jdk中有一个直接关连的类Properties,接下来我们来看一下它的用法
289 0
|
Java
基于ResourceLoader读取Properties配置文件
基于ResourceLoader读取Properties配置文件
228 0
|
Java Spring
Spring @Value:读取Properties配置文件
Spring @Value:读取Properties配置文件
242 0
Spingboot 读取 yml 配置文件里的参数值
Spingboot 读取 yml 配置文件里的参数值
159 0
|
XML C# 数据格式
c#读取配置文件,C#读xml配置文件,c# 配置文件,C# 读取xml
c#读取配置文件,C#读xml配置文件,c# 配置文件,C# 读取xml
618 0