试问,一篇文章一半的字不认识,你能理解讲了什么故事吗?Spring中大部分的类你都陌生,你能读懂?顶多是死记硬背罢了!
最佳打开方式:自己一边手动翻看源码,一边对照阅读。文章中粘出的代码都很容易,慢慢啃,绝对有收获!
一、PropertySources
PropertySources包含了一个或者多个PropertySource。上篇文章讲述了PropertySource,是用来存储属性资源的类,不了解的可以先阅读上一篇:Spring源码阅读之PropertySource_LookOutThe的博客-CSDN博客
PropertySources是一个接口,源码如下:
public interface PropertySources extends Iterable<PropertySource<?>> {
default Stream<PropertySource<?>> stream() {
return StreamSupport.stream(spliterator(), false);
}
boolean contains(String name);
@Nullable
PropertySource<?> get(String name);
}
主要方法有2个,第一个是判断是否包含指定名字的PropertySource,另一个是根据名字获取PropertySource。
此外该接口继承自Iterable接口,可以像list一样调用foreach、使用Iterator、使用Stream。
整个类关系图如下所示:
很开心,只有一个子类,哈哈,下面我们就看看这个子类的内容吧。
二、MutablePropertySources
这里放出关键代码帮助理解:
public class MutablePropertySources implements PropertySources {
private final List<PropertySource<?>> propertySourceList = new CopyOnWriteArrayList<>();
@Override
public Iterator<PropertySource<?>> iterator() {
return this.propertySourceList.iterator();
}
@Override
public Spliterator<PropertySource<?>> spliterator() {
return Spliterators.spliterator(this.propertySourceList, 0);
}
@Override
public Stream<PropertySource<?>> stream() {
return this.propertySourceList.stream();
}
@Override
public boolean contains(String name) {
for (PropertySource<?> propertySource : this.propertySourceList) {
if (propertySource.getName().equals(name)) {
return true;
}
}
return false;
}
@Override
@Nullable
public PropertySource<?> get(String name) {
for (PropertySource<?> propertySource : this.propertySourceList) {
if (propertySource.getName().equals(name)) {
return propertySource;
}
}
return null;
}
}
类中最能说明该类作用的地方就是开头定义的List,使用的是CopyOnWriteArrayList。
CopyOnWriteArrayList
这个list在添加元素的时候会加锁、并将原数组重新拷贝一份。线程安全。
类中的方法都是操作list相关的方法,这里就不一一说明了。
三、使用
这个类要和PropertySource放在一起使用,我们写个简单的例子:
class Test{
public static void main(String[] args) {
MutablePropertySources sources = new MutablePropertySources();
sources.addFirst(new RandomValuePropertySource("random"));
sources.addLast(new MapPropertySource("map", new HashMap<>(1)));
sources.forEach(item -> {
System.out.println(item.getName());
});
System.out.println(sources.get("map"));
System.out.println(sources.size());
sources.remove("random");
System.out.println(sources.size());
}
}
例子代码也很简单,和操作普通的List几乎一样。
四、总结
上一篇文章中的PropertySource存储的是属性资源,本文中的PropertySources通过list存储多个PropertySource。并提供了类似List集合的多种操作集合的方法。
觉得有帮助的同学不妨点个赞吧!你的支持是我写作的最大动力,谢谢!