properties配置文件的读取

Dear 丶 2023-10-16 20:39 102阅读 0赞

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

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

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

二、spring MVC Controller加载方式:
1、首先在applicationContext.xml配置

  1. <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  2. <property name="locations" >
  3. <list>
  4. <value>classpath:config/configure.properties</value>
  5. </list>
  6. </property>
  7. </bean>
  8. <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
  9. <property name="properties" ref="configProperties" />
  10. </bean>

configure.properties是你的文件名,config是配置文件所在的目录,
结构 ![Image 1][]

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

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

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

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

三、通过ResourceBundle来加载

示例代码:

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

创建一个默认的ResourceBundle对象
ResourceBundle会查找WEB-INF\classes\下的config.properties的文件
它跟普通java类的命名规则完全一样:
- 区分大小写
- 扩展名 .properties 省略。就像对于类可以省略掉 .class扩展名一样
- 资源文件必须位于指定包的路径之下(位于所指定的classpath中)
假如你是在非Web项目中使用,则一定要写资源文件的路径,也就是包路径必须存在。
如果是Web项目,不写包路径可以,此时将资源文件放在WEB-INF\classes\目录下就可以。

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

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

四、通过spring框架来读取

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

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

[Image 1]:

发表评论

表情:
评论列表 (有 0 条评论,102人围观)

还没有评论,来说两句吧...

相关阅读

    相关 properties配置文件读取

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

    相关 读取Properties配置文件

    通过读取properties文件获取配置项的值在开发中是很常用的,这种方式降低了变量和代码间的耦合,使得非开发人员也可以很容易的对系统的一些配置进行修改,比如配置数据库连接参数