• spring读取properties文件


    项目中的一些灵活配置,设置到properties文件中,项目中通过读取properties中相应的值来使用,修改时,也只修改properties即可。以上为使用的好处,现在,总结一下项目中propeties文件的使用。

    一、Java直接读取properties

    二、spring管理properties

    三、自定义PropertyPlaceholderConfigurer

    第一种,java直接读取的方式有很多种,主要思路就是通过inputStream读取到properties文件,获取值并应用。主要代码:

    [java] view plain copy
     
    1. <pre name="code" class="java">Properties properties = new Properties();  
    2. InputStream in = Object.class.getResourceAsStream("properties的路径");  
    3. properties.load(in);   
    [java] view plain copy
     
    1. 现在,通过properties可以取到值并应用了。  

    第二种,spring管理

    spring主要是通过PropertyPlaceholderConfigurer类来管理。该类是个bean工厂后置处理器的实现,也就是 BeanFactoryPostProcessor接口的一个实现。PropertyPlaceholderConfigurer可以将上下文(配置文 件)中的属性值放在另一个单独的标准java Properties文件中去。

    下面看一段我们都熟悉的代码:

    [html] view plain copy
     
    1. <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    2.     <property name="locations">  
    3.         <list>  
    4.             <value>classpath*:config/jdbc.properties</value>  
    5.             <value>classpath*:config/default.properties</value>  
    6.         </list>  
    7.     </property>  
    8. </bean>  
    [html] view plain copy
     
    1. <pre name="code" class="html"><bean id="dataSource"    
    2.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">    
    3.         <property name="driverClassName" value="${jdbc.driverClassName}" />    
    4.         <property name="url" value="${jdbc.url}" />    
    5.         <property name="username" value="${jdbc.username}" />    
    6.         <property name="password" value="${jdbc.password}" />    
    7.  </bean>    

    在我们的service或者action中使用时,也是同样,将properties中的key写到对应bean的配置中。

    1. <bean id="userIService" class="com.upCloud.service.UserServiceImpl">  
    2.     <property name="default1" value="${default1}" />  
    3. </bean>  
     
      1. 在bean中配置之后,在userServiceImpl.java中注入default1即可使用了。 
  • 相关阅读:
    git 实践(二) push的使用
    git 实践(一) pull的使用
    redux项目实战应用笔录
    浅谈ES6的Object.assign()浅拷贝
    React下reducer中处理数组&&对象的赋值改动
    git pull与git clone
    (0)网络编程基础(网络基本知识)
    (1)什么是socket(套接字)
    (12)异常处理
    (11)类的内置函数
  • 原文地址:https://www.cnblogs.com/wangcp-2014/p/6039297.html
Copyright © 2020-2023  润新知