Spring如何使用PropertyPlaceholderConfigurer读取文件
这篇文章主要介绍了Spring如何使用PropertyPlaceholderConfigurer读取文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
一.简介
大型项目中,我们往往会对我们的系统的配置信息进行统一管理,一般做法是将配置信息配置与一个cfg.properties的文件中,然后在我们系统初始化的时候,系统自动读取cfg.properties配置文件中的keyvalue(键值对),然后对我们系统进行定制的初始化。
那么一般情况下,我们使用的java.util.Properties,也就是java自带的。往往有一个问题是,每一次加载的时候,我们都需要手工的去读取这个配置文件,一来编码麻烦,二来代码不优雅,往往我们也会自己创建一个类来专门读取,并储存这些配置信息。
对于web项目来说,可以通过相对路径得到配置文件的路径,而对于可执行项目,在团队开发中就需要根据各自的环境来指定properties配置文件的路径了。对于这种情况可以将配置文件的路径放在java虚拟机JVM的自定义变量(运行时参数)中,例如:-Ddev.config=/dev.properties寻找的是本机根目录下
Spring中提供着一个PropertyPlaceholderConfigurer,这个类是BeanFactoryPostProcessor的子类。其主要的原理在是。Spring容器初始化的时候,会读取xml或者annotation对Bean进行初始化。初始化的时候,这个PropertyPlaceholderConfigurer会拦截Bean的初始化,初始化的时候会对配置的${pname}进行替换,根据我们Properties中配置的进行替换。从而实现表达式的替换操作。
二.XML方式
方式1
classpath:db.properties classpath:db2.properties
#db.properties jdbc.driverClass==net.sourceforge.jtds.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test? jdbc.username=anqi jdbc.password=123456
#db2.properties name=anqi age=23
importorg.junit.Test;importorg.junit.runner.RunWith; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.test.context.ContextConfiguration; importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring-context.xml") publicclassTestPropertyPlaceHoder2{ @Value("${jdbc.username}") privateStringusername; @Value("${jdbc.password}") privateStringpassword; @Value("${name}") privateStringname; @Value("${age}") privateintage; @Test publicvoidtestResource(){ System.out.println("username:"+username); System.out.println("password:"+password); System.out.println("name:"+name); System.out.println("age:"+age); } } /*username:anqipassword:123456name:anqiage:23*/
方式2
注意:我们知道不论是使用PropertyPlaceholderConfigurer还是通过context:property-placeholder这种方式进行实现,都需要记住,Spring框架不仅仅会读取我们的配置文件中的键值对,而且还会读取Jvm初始化的一下系统的信息。有时候,我们需要将配置Key定一套命名规则,例如
jdbc.username
jdbc.password
同时,我们也可以使用下面这种配置方式进行配置,这里我配NEVER的意思是不读取系统配置信息。
- SYSTEM_PROPERTIES_MODE_FALLBACK:在解析一个占位符的变量的时候。假设不能获取到该变量的值。就会拿系统属性来尝试,
- SYSTEM_PROPERTIES_MODE_OVERRIDE:在解析一个占位符的时候。会先用系统属性来尝试,然后才会用指定的属性文件,
- SYSTEM_PROPERTIES_MODE_NEVER:从来都不会使用系统属性来尝试。
三.Java编码方式
采取编码的方式显然更加灵活,当我们在做一个项目时,在线下本地跑和在服务器线上跑时,需要的参数肯定有诸多不同,我们可以通过xmljava编码的方式来指定采用哪一个配置方案,同一个配置方案中也可以将线上配置文件的地址放在前面,没有线上配置文件就采用本地配置的方式来运行项目。
spring-context.xml
classpath:db.properties classpath:db2.properties
classpath:db3.properties
db.properties
jdbc.driverClass==net.sourceforge.jtds.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test? jdbc.username=anqijdbc. password=123456 pro=1 version=db1
db2.properties
name=anqi age=23 pro=2 version=db2
db3.properties
pro=3
dev.properties
company=abcversion=dev.config
读取配置的工具类
importorg.springframework.beans.factory.config.PropertyPlaceholderConfigurer; importorg.springframework.core.io.FileSystemResource; importorg.springframework.core.io.Resource; importjava.io.File; importjava.io.IOException; importjava.util.*; publicclassPropertiesUtilextendsPropertyPlaceholderConfigurer{ privatestaticResourceelectResource; privatestaticPropertiesconfigProperties=newProperties(); privatestaticPropertiesprogramProperties=newProperties(); publicPropertiesUtil(){} /** *根据spring-context配置文件中的配置,来将项目下对应的properties文件加载到系统中 *并且经过特殊处理db2.properties不允许覆盖掉db1.properties中相同的key *@paramlocations */ publicvoidsetLocations(Resource...locations){ ListexistResourceList=newArrayList<>(); ResourcedevConfig=getDevConfig(); if(devConfig!=null){ existResourceList.add(devConfig); } Resourceresource; for(inti=0;i 1){ for(inti=existResourceList.size()-2;i>=0;--i){ PropertiesbackupConfig=newProperties(); //从后往前加载db1db2 backupConfig.load(((Resource)existResourceList.get(i)).getURL().openStream()); Iteratoriterator=backupConfig.keySet().iterator(); //通过后面新添加的db3.properties、db4.peoperties进行更新db.properties //添加没有的key不能覆盖前面的key while(iterator.hasNext()){ Objectkey=iterator.next(); if(!configProperties.containsKey(key)){ configProperties.put(key,backupConfig.get(key)); } } } } }catch(IOExceptione){ e.printStackTrace(); } } /** *将programConfig的配置方案加载到programeConfig中 *(即将db3.properties加载到programeConfig) *包含运行时方案(运行时配置优先级最高)会覆盖key相同的value *@paramlocations */ publicvoidsetProgramConfig(Resource...locations){ List existResourceList=newArrayList<>(); Resourceresource; for(inti=0;i iterator=existResourceList.iterator(); while(iterator.hasNext()){ resource=iterator.next(); programProperties.load(resource.getURL().openStream()); } }catch(IOExceptione){ e.printStackTrace(); } } ResourcedevConfig=getDevConfig(); if(devConfig!=null){ try{ PropertiesdevProperties=newProperties(); devProperties.load(devConfig.getURL().openStream()); Iteratoriterator=devProperties.keySet().iterator(); while(iterator.hasNext()){ Objectkey=iterator.next(); programProperties.put(String.valueOf(key), devProperties.getProperty(String.valueOf(key),"")); } }catch(Exceptione){ e.printStackTrace(); } } } /** *在运行期间传入配置参数(可以将配置文件放在本机或服务器上) *@return */ privatestaticResourcegetDevConfig(){ Strings=System.getProperty("dev.config",""); FiledevConfig=newFile(s); return!s.trim().equals("")&&devConfig.exists()&&devConfig.isFile()? newFileSystemResource(s):null; } /** *外部访问properties配置文件中的某个key *@paramkey *@return */ publicstaticStringget(Stringkey){ returnprogramProperties.containsKey(key)? programProperties.getProperty(key):configProperties.getProperty(key); } publicstaticvoidshow(){ System.out.println("db_1keys:"+configProperties.keySet()); System.out.println("db_2keys:"+programProperties.keySet()); } }
测试类
packagecom.anqi.testPropertyPlaceHoder; importorg.springframework.context.ApplicationContext; importorg.springframework.context.support.ClassPathXmlApplicationContext; publicclassTestPropertyPlaceHoder{ publicstaticvoidmain(String[]args){ ApplicationContextal=newClassPathXmlApplicationContext("classpath:spring-context.xml"); PropertiesUtil.show(); System.out.println(PropertiesUtil.get("version")); //-Ddev.config=/dev.properties传入运行时参数 System.out.println(PropertiesUtil.get("company")); System.out.println(PropertiesUtil.get("pro")); //db_1keys:[name,jdbc.password,version,company,jdbc.url,pro,jdbc.driverClass,jdbc.username,age] //db_2keys:[company,version,pro] //dev.config //abc //3 } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。