spring中的MutablePropertySources类设计

刚看到MutablePropertySources这个类中有一段示例感觉蛮有意思的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
* Customize the set of {@link PropertySource} objects to be searched by this
* {@code Environment} during calls to {@link #getProperty(String)} and related
* methods.
*
* <p>Subclasses that override this method are encouraged(鼓励) to add property
* sources using {@link MutablePropertySources#addLast(PropertySource)} such that
* further subclasses may call {@code super.customizePropertySources()} with
* predictable(可预测的) results. For example:
* public class Level1Environment extends AbstractEnvironment {
* @Override
* protected void customizePropertySources(MutablePropertySources propertySources) {
//没有来自基类的操作 no-op from base class
* super.customizePropertySources(propertySources);
* propertySources.addLast(new PropertySourceA(...));
* propertySources.addLast(new PropertySourceB(...));
* }
* }

* public class Level2Environment extends Level1Environment {
* @Override
* protected void customizePropertySources(MutablePropertySources propertySources) {
//从超类中全部 添加 add all from superclass
* super.customizePropertySources(propertySources);
* propertySources.addLast(new PropertySourceC(...));
* propertySources.addLast(new PropertySourceD(...));
* }
* }
* </pre>
* In this arrangement, properties will be resolved against sources A, B, C, D in that
* order. That is to say that property source "A" has precedence over property source
* "D". If the {@code Level2Environment} subclass wished to give property sources C
* and D higher precedence than A and B, it could simply call
* {@code super.customizePropertySources} after, rather than before adding its own:
* <pre class="code">
* public class Level2Environment extends Level1Environment {
* @Override
* protected void customizePropertySources(MutablePropertySources propertySources) {
* propertySources.addLast(new PropertySourceC(...));
* propertySources.addLast(new PropertySourceD(...));
* super.customizePropertySources(propertySources);
// add all from superclass
* }
* }

也就是继承AbstractEnvironment类最主要目的是要通过customizePropertySources添加属性资源,而且在子类中调用积累的customizePropertySources将决定属性的优先级关系。

除了这些操作,我们还可以像之前的文章中说得那样可以通过ApplicationContextInitializer中的initialize方法中去获取MutableProperties然后再调用addLast或其他方法。

欢迎关注我的公众号:沉迷Spring
显示 Gitment 评论
0%