使用spring工厂读取property配置文件示例代码
本文将介绍两种Spring读取property配置文件的方法,接下来看看具体内容。
一、通过Spring工厂读取
示例:
publicclassPropertyConfig{
privatestaticAbstractBeanFactorybeanFactory=null;
privatestaticfinalMapcache=newoncurrentHashMap<>();
@Inject
publicPropertyConfig(AbstractBeanFactorybeanFactory){
this.beanFactory=beanFactory;
}
/**
*根据key获取配置文件的Value
*@paramkey*@return
*/
publicstaticStringgetProperty(Stringkey){
StringpropValue="";
if(cache.containsKey(key)){
propValue=cache.get(key);
}else{
try{
propValue=beanFactory.resolveEmbeddedValue("${"+key.trim()+"}");
cache.put(key,propValue);
}
catch(IllegalArgumentExceptionex){
ex.printStackTrace();
}
}
returnpropValue;
}
}
Springxml的配置
classpath:props/${property-path}.properties classpath:important.properties
在项目中使用
StringmaxTimeInSecondsProp=PropertyConfig.getProperty("maxTimeInSeconds");
二、直接使用spirng程序代码读取项目的配置文件方法
importorg.springframework.core.io.ClassPathResource;
importorg.springframework.core.io.Resource;
importorg.springframework.core.io.support.PropertiesLoaderUtils;
importorg.springframework.core.io.FileSystemResource;
publicclassTest{
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
StringconfigFile="D:/test/application.properties";
//如果配置文件在classpath目录下可以使用ClassPathResource对象
//Resourceresource=newClassPathResource("/application.properties");
Resourceresource=newFileSystemResource(configFile);
try{
Propertiesproperty=PropertiesLoaderUtils.loadProperties(resource);
Stringdriver=property.getProperty("jdbc.driver");
Stringurl=property.getProperty("jdbc.url");
StringuserName=property.getProperty("jdbc.username");
Stringpassword=property.getProperty("jdbc.password");
}
catch(IOExceptione1){
//log.error("readconfigfilefailed",e1);
}
}
}
如果配置文件在classpath目录下可以使用ClassPathResource对象
Resourceresource=newClassPathResource("/application.properties");
总结
以上就是本文关于使用spring工厂读取property配置文件示例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。