PropertySource解析
PropertySource用途
org.springframework.core.env.PropertySource
顾名思义就是属性源的意思,再具体一点就是对获取键值对资源的抽象类.
从类结构信息可以看出主要包含containesProperty(String),getProperty(String),getName(),getSource()这几个方法,其中通过getSource()获取的source可以是任何封装了属性集的类型(eg:Map,Properties,Redis客户端,Zookeeper客户端等)。相应的实现类有MapPropertySource、PropertiesPropertySource等,对于基于Redis、Zookeeper我们可以自己来进行实现
但是一般情况下不会单独使用PropertySource,而是通过PropertySources来获取相关属性
PropertySources
PropertySources聚合了PropertySource,提供了property的多数据源访问。其中MutablePropertySources
是PropertySources的默认实现,org.springframework.core.env.Environment
的子接口ConfigurableEnvironment
的属性源就是MutablePropertySources
。
/**
* Return the {@link PropertySources} for this {@code Environment} in mutable form,
* allowing for manipulation of the set of {@link PropertySource} objects that should
* be searched when resolving properties against this {@code Environment} object.
* The various {@link MutablePropertySources} methods such as
* {@link MutablePropertySources#addFirst addFirst},
* {@link MutablePropertySources#addLast addLast},
* {@link MutablePropertySources#addBefore addBefore} and
* {@link MutablePropertySources#addAfter addAfter} allow for fine-grained control
* over property source ordering. This is useful, for example, in ensuring that
* certain user-defined property sources have search precedence over default property
* sources such as the set of system properties or the set of system environment
* variables.
* @see AbstractEnvironment#customizePropertySources
*/
MutablePropertySources getPropertySources();
MutablePropertySources
mutable本意是可变的,我们可以在运行时添加PropertySource来进行动态的扩展
其中addFirst、addLast、addBefore、addAfter赋予了PropertySources控制属性源获取的权限,比如我们可以编写自定义的属性使之优先级高于默认的属性源.具体可查看示例代码
PropertySource使用示例
使用Map自定义属性源
Map<String,Object> customerSource;
@Before
public void before(){
customerSource = new HashMap<>();
customerSource.put("hello", "chenye");
customerSource.put("name", "sxx");
}
/**
* 使用map作为属性源
*/
@Test
public void testMapPropertySource(){
PropertySource mapSource = new MapPropertySource("mapSource", customerSource);
assertEquals("chenye",mapSource.getProperty("hello"));
}
使用MutablePropertySources测试如果优先获取自定义的属性而非系统属性
/**
* 通过 addLast、addFist方法设置属性源的优先级
*/
@Test
public void testPropertySources(){
MapPropertySource systemPropertySource = new MapPropertySource("systemProperties", (Map) System.getProperties());
MutablePropertySources pss = new MutablePropertySources();
pss.addLast(systemPropertySource);
/**
* 自定义系统属性变量,调用addFirst方法使之优先级高于系统属性源
*/
customerSource.put("user.name", "sxx");
pss.addFirst(new MapPropertySource("customerProperties",customerSource));
assertEquals("sxx",fetchPropertyValue(pss,"user.name"));
// printPropertySources(systemPropertySource);
}