PropertySource
PropertySource
类 设计用来存放<key,value>
对象的抽象类。同时name
,source
都是final在初始化后不在变化,
protected final String name;
protected final T source;
getProperty
是个抽象方法,需要在子类来实现。
equals
方法解读,
// 当对比对象与 当前对象恒等,或者name相等,则判断相等。
@Override
public boolean equals(Object obj) {
return (this == obj || (obj instanceof PropertySource &&
ObjectUtils.nullSafeEquals(this.name, ((PropertySource<?>) obj).name)));
}
named()
// 根据name 创建一个 子类 ComparisonPropertySource 对象
public static PropertySource<?> named(String name) {
return new ComparisonPropertySource(name);
}
ComparisonPropertySource
静态内部类
// StubPropertySource 继承自 PropertySource 实现 `getProperty` 返回null
// ComparisonPropertySource 继承 StubPropertySource 除构造函数为全部抛出异常,一般用来创建一个具名 PropertySource
static class ComparisonPropertySource extends StubPropertySource {
private static final String USAGE_ERROR =
"ComparisonPropertySource instances are for use with collection comparison only";
public ComparisonPropertySource(String name) {
super(name);
}
@Override
public Object getSource() {
throw new UnsupportedOperationException(USAGE_ERROR);
}
@Override
public boolean containsProperty(String name) {
throw new UnsupportedOperationException(USAGE_ERROR);
}
@Override
public String getProperty(String name) {
throw new UnsupportedOperationException(USAGE_ERROR);
}
}
示例代码
List<PropertySource<?>> sources = new ArrayList<PropertySource<?>>();
sources.add(new MapPropertySource("sourceA", mapA));
sources.add(new MapPropertySource("sourceB", mapB));
sources.contains(PropertySource.named("sourceA"));
sources.contains(PropertySource.named("sourceB"));
!sources.contains(PropertySource.named("sourceC"));
}
PropertySource 类重写了equals方法,named 创建一个具名的 对象
EnumerablePropertySource
// 重写 containsProperty 方法
@Override
public boolean containsProperty(String name) {
return ObjectUtils.containsElement(getPropertyNames(), name);
}
// 添抽样 方法,用来返回 value的 name
public abstract String[] getPropertyNames();
MapPropertySource
以Map的形式保存 source
public class MapPropertySource extends EnumerablePropertySource<Map<String, Object>> {
public MapPropertySource(String name, Map<String, Object> source) {
super(name, source);
}
@Override
public Object getProperty(String name) {
return this.source.get(name);
}
@Override
public boolean containsProperty(String name) {
return this.source.containsKey(name);
}
@Override
public String[] getPropertyNames() {
return StringUtils.toStringArray(this.source.keySet());
}
}