• 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();//获取属性文件的某一个内容
    

      

  • 相关阅读:
    vba create rectangle 矩形
    (zz)nnotation学习笔记2:关于Annotation与符号,还是要读arcmap帮助!!!
    backgroundworker
    C# , mongodb ,study
    工作中常用的dos命令 数据处理经验总结
    你需要明白的SQL SERVER书签查找(Bookmark Lookup)
    使用CalendarExtender
    js控制5秒后页面自动跳转
    HTML按秒数的页面跳转
    序列化与反序列化读取保存xml文件
  • 原文地址:https://www.cnblogs.com/feitianshaoxai/p/6598808.html
Copyright © 2020-2023  润新知