zoukankan      html  css  js  c++  java
  • spring加载属性配置文件内容

    在spring中提供了一个专门加载文件的类PropertyPlaceholderConfigurer,通过这个类我们只需要给定需要加载文件的路径就可以

    通过该类加载到项目,但是为了后面在程序中需要使用到属性文件内容,在这里将加载到的配置文件全部保存进一个map对象中,后面可以直接

    键值对去用:

    首先创建一个继承PropertyPlaceholderConfigurer的类PropertyConfigurer,加载文件,并保存进对象:

    public class PropertyConfigurer extends PropertyPlaceholderConfigurer{
    
    	private static Map<String, Object> ctxPropertiesMap; 
    	
        @Override 
        protected void processProperties( ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
            //spring载入配置文件(具体原理还在研究中)
        	super.processProperties(beanFactoryToProcess, props); 
            ctxPropertiesMap = new HashMap<String, Object>(); 
            //便利加载的配置文件的键值,并根据键值获取到value值,然后一同保存进map对象
            for (Object key : props.keySet()){
                String keyStr = key.toString(); 
                String value = props.getProperty(keyStr); 
                ctxPropertiesMap.put(keyStr, value);
            }
        } 
     
        //此方法根据map对象的键获取其value的值
        public static Object getContextProperty(String name) { 
            return ctxPropertiesMap.get(name);
        } 
    }
    

      然后在spring的配置文件中配置需要载入的属性文件

     <!--读入配置文件,在后面的代码中需要用到属性文件的内容时 -->
    	<bean id="propertyConfigurer"  class="cn.com.owg.util.PropertyConfigurer">
    	     <property name="locations">
    		<value>classpath*:jdbc.properties</value>
    	     </property>
    	</bean>
    	

     <!--读入配置文件,后面的代码不需要用到属性文件的内容时,直接通过PropertyPlaceholderConfigurer来载入属性文件 -->
            <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
                 <property name="locations">
                         <value>classpath*:jdbc.properties</value>
                 </property>
            </bean>

    	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  destroy-method="close">  
             <property name="driverClassName" value="${jdbc.driverClassName}" />
             <property name="url" value="${jdbc.url}" />
             <property name="username" value="${jdbc.username}" />
             <property name="password" value="${jdbc.password}" />
        </bean> 
    

      后面的代码中需要使用属性配置文件时:

    String    driverManager=PropertyConfigurer.getContextProperty("jdbc:driverClassManager")).trim();//获取属性文件的某一个内容
    

      

  • 相关阅读:
    HDU 5280 Senior's Array (暴力,水)
    LeetCode Intersection of Two Linked Lists (找交叉点)
    LeetCode Pascal's Triangle II (杨辉三角)
    LeetCode Lowest Common Ancestor of a Binary Search Tree (LCA最近公共祖先)
    LeetCode Binary Tree Level Order Traversal (按层收集元素)
    LeetCode Balanced Binary Tree (判断平衡树)
    LeetCode Maximum Depth of Binary Tree (求树的深度)
    LeetCode Palindrome Linked List (回文链表)
    jstl表达式的应用的条件
    dao层写展示自己需要注意的问题
  • 原文地址:https://www.cnblogs.com/feitianshaoxai/p/6598808.html
Copyright © 2011-2022 走看看