springboot在静态代码块中读取ties配置⽂件⾥的值
描述
最近在项⽬中发现⼀个变量总是修改。就想着将参数给提取到ties配置⽂件⾥。后来运⾏代码后发现使⽤@Value注解
读出来的数据为null,后来发现需要读取的属性是静态的。
解决⽅案
添加两个⼯具类。使⽤⼯具类来获取配置⽂件中的参数。
PropertiesLoader:
;
Factory;
tResourceLoader;
ce;
ceLoader;
ption;
tream;
ElementException;
ties;
publicclassPropertiesLoader{
privatestaticLoggerlogger=ger();
privatestaticResourceLoaderresourceLoader=newDefaultResourceLoader();
privatefinalPropertiesproperties;
publicPropertiesLoader(String...resourcesPaths){
ties=operties(resourcesPaths);
}
publicPropertiesgetProperties(){
ties;
}
privateStringgetValue(Stringkey){
StringsystemProperty=perty(key);
if(systemProperty!=null){
returnsystemProperty;
}el{
nsKey(key)?perty(key):"";
}
}
publicStringgetProperty(Stringkey){
Stringvalue=ue(key);
if(value==null){
thrownewNoSuchElementException();
}el{
returnvalue;
}
}
publicStringgetProperty(Stringkey,StringdefaultValue){
Stringvalue=ue(key);
returnvalue!=null?value:defaultValue;
}
publicIntegergetInteger(Stringkey){
Stringvalue=ue(key);
if(value==null){
if(value==null){
thrownewNoSuchElementException();
}el{
f(value);
}
}
publicIntegergetInteger(Stringkey,IntegerdefaultValue){
Stringvalue=ue(key);
returnvalue!=null?f(value):defaultValue;
}
publicDoublegetDouble(Stringkey){
Stringvalue=ue(key);
if(value==null){
thrownewNoSuchElementException();
}el{
f(value);
}
}
publicDoublegetDouble(Stringkey,IntegerdefaultValue){
Stringvalue=ue(key);
returnvalue!=null?f(value):(double)defaultValue;
}
publicBooleangetBoolean(Stringkey){
Stringvalue=ue(key);
if(value==null){
thrownewNoSuchElementException();
}el{
f(value);
}
}
publicBooleangetBoolean(Stringkey,booleandefaultValue){
Stringvalue=ue(key);
returnvalue!=null?f(value):defaultValue;
}
privatePropertiesloadProperties(String...resourcesPaths){
Propertiesprops=newProperties();
String[]var3=resourcesPaths;
intvar4=;
for(intvar5=0;var5
Stringlocation=var3[var5];
InputStreamis=null;
try{
Resourceresource=ource(location);
is=utStream();
(is);
}catch(IOExceptionvar12){
("Couldnotloadpropertiesfrompath:"+location+","+sage());
}finally{
try{
if(is!=null){
();
}
}catch(Exceptione){
tackTrace();
}
}
}
returnprops;
}
}
PropertiesUtil:
;
;
publicclassPropertiesUtil{
privatestaticMap
privatestaticPropertiesLoaderloader=newPropertiesLoader(newString[]{"ties"});
publicstaticStringgetConfig(Stringkey){
Stringvalue=(key);
if(value==null){
value=perty(key);
(key,value!=null?value:"");
}
returnvalue;
}
}
配置⽂件
调⽤
static{
try{
Stringparticipates=fig("participates");
}catch(Exceptione){
("加载配置出错:{}",sage());
}
}
欢迎⼤家访问我的个⼈博客:
本文发布于:2022-11-28 04:35:37,感谢您对本站的认可!
本文链接:http://www.wtabcd.cn/fanwen/fan/88/36966.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |