我们使用A.Spring知识点A.Spring从3.1版开始添加了配置环境和属性资源。
配置环境
Spring的应用上下文包括实现可配置环境接口的环境
可配置环境本身包含许多属性资源处理器
属性来源
请注意,可以理解为许多Key - Value的属性配置,PropertySource之间具有优先级,如果多个PropertySource中存在一个Key,则上一个PropertySource优先。
B.Spring的BeanFactoryPostProcessor
在标准初始化后,修改APP应用程序上下文中的内部bean工厂。 的所有bean定义都已加载,但未实例化。 这样可以覆盖和添加属性。 此外,它还可以用于尽快初始化的bean。
也就是说,使用Spring,BeanFactoryPostProcessor可以在容器实例化其他bean之前读取配置元数据,并根据需要进行修改,因此在此添加自定义的属性源。
C.Spring的环境硬件。 用于获取可配置环境
另外,还必须提到Aware接口。 这实际上是空接口,不包括方法。 这表示感知到的含义,可以从接口中检索指定的对象,例如:
使用BeanFactoryAware获取BeanFactory使用应用程序上下文获取应用程序上下文使用BeanNameAware获取BeanName等
2 .主要实现代码如下: 1 .自定义类属性源处理器,角色:在实例化之前添加自定义属性源
@Component
publicclasspropertysourcesprocessorimplementsbeanfactorypostprocessor,环境硬件{
私有配置策略环境保护;
@Override
publicvoidpostprocessbeanfactory (可配置列表可配置beanfactoryconfigurablelistablebeanfactory ) throwsBeansException {
if (! this.environment.getproperty sources ().contains('test ' ) }{
//PropertySourceT的通用类型。 在这个类中,获取外部参数
readsettingsreadsettings=newreadsettings (;
//实例化自定义的属性源
configpropertysourcepropertysource=newconfigpropertysource (' test ',readSettings );
将属性源添加到spring环境
this.environment.getproperty sources ().addfirst(propertysource );
}
}
@Override
公共环境环境。
this.environment=(配置环境) environment;
}
}
2 .自定义类ConfigPropertySource,继承EnumerablePropertySource类,重写角色: getProperty方法,读取外部部署
publicclassconfigpropertysourceextendsenumerablepropertysourcereadsettings {
publicconfigpropertysource (字符串名称,读取设置源) {
super(name,source );
}
@Override
公共字符串[ ] getproperty names {
setstring keys=this.source.getkeys (;
return keys.to array (new string [ keys.size (];
}
重写getProperty方法,从ReadSettings中获取value值
@Override
publicobjectgetproperty{
returnthis.source.readvalue(s;
}
}
3 .自定义类ReadSettings,角色:装入外部资源功能类
publicclassReadSettings {
privatepropertiespro=new properties (;
publicstringreadvalue (字符串名称)。
try{
//这里也可以通过HTTP请求远程读取配置文件
pro=newProperties (;
inputstream in=newbufferedinputstream (新文件inputstream (c :usersadministratordesktop222 )
pro.load(in;
字符串属性=pro.getproperty (name;
返回属性;
}catch(ioexceptione ) {
e .打印堆栈跟踪(;
}
returnSystem.currentTimeMillis () ';
}
公共设置获取密钥(
SetString keys=newHashSet (;
Iterator i$=pro.entrySet ().iterator );
while(I$.Hasnext ) ) ) ) )。
Map.EntryObject,objecte=(map.entry ) i$.next );
kys.add(e.getkey ).toString );
}
返回键;
}
}
使用配置文件时,请直接使用@Value注释。
浏览Apolloconfigurationcenter以启动客户端读取远程配置文件的方法
3359 Ctrip corp.github.io/Apollo/#/zh/design/Apollo-design? 与id=_31-spring集成的原理