zoukankan      html  css  js  c++  java
  • Java Bean 获取properties文件的读取

    实际的开发过程中,将一些配置属性从java代码中提取到properties文件中是个很好的选择,降低了代码的耦合度。下面介绍两种通过spring读取properties文件的方法,以ip地址配置为例。ip.properties文件:

    host=127.0.01
    port=8080
     1、 使用org.springframework.beans.factory.config.PropertyPlaceholderConfigurer 类解析,在applicationContenxt.xml添加配置:
               <value>classpath*:/ip.properties</value>  
         这样可以在其他bean定义中使用:<property name="host" value="${host}" />
         另外一种通过bean的@value注解实现:
       1:  import org.springframework.beans.factory.annotation.Value;
       2:  import org.springframework.stereotype.Component;
       3:   
       4:  @Component
       5:  public class Sample{
       6:   
       7:      @Value("${host}")
       8:      private String host;
       9:      @Value("${port}")
      10:      private String port;
      11:  }
    然后注入Sample 对象即可:
    @Autowired
    private Sample sample;

    2、使用org.springframework.core.io.support.PropertiesLoaderUtils 类来加载properties文件

       1:  import org.springframework.core.io.ClassPathResource;
       2:  import org.springframework.core.io.Resource;
       3:  import org.springframework.core.io.support.PropertiesLoaderUtils;
       4:   
       5:  Resource resource = new ClassPathResource("/ip.properties");
       6:          Properties props = PropertiesLoaderUtils.loadProperties(resource);
       7:          Set<Object> keys = props.keySet();
       8:          for(Object key : keys){
       9:              System.out.println(key+" : "+props.get(key));
      10:          }
     
    两种方法输出结果:

    port : 8080
    host : 127.0.01

  • 相关阅读:
    guid与Base64编码互相转换
    xml序列化与反序列化工具
    Win10 15063 开始运行不保存历史记录原因和解决方法
    win10 localhost 解析为 ipv6地址 ::1 的解决办法
    在VisualStudio中应该使用什么字体
    S7-200系列PLC与WINCC以太网通信CP243i的实例
    超棒的 15 款 Bootstrap UI 编辑器
    NuGet学习笔记(转)
    SQLServer公历转农历函数(1900年-2049年)
    WPF 的datagrid 列名中没有显示下划线是怎么回事?
  • 原文地址:https://www.cnblogs.com/jason0529/p/3413520.html
Copyright © 2011-2022 走看看