杀死Spring - Spring系列的${}占位符处理类PropertyPlaceholderConfigurer
我们知道,在spring的xml配置文件可以使用${}这样的占位符来引入变量值,那么他是怎么实现这样的功能的呢?
它主要是通过PropertyPlaceholderConfigurer类来实现这一功能。
惯例,我们贴出他的继承关系图:
类图说明:
1Ordered:由于一个接口可以有多个实例,该接口实现这些实例的排序
2PriorityOrdered:优先级比Ordered高
3BeanFactoryPostProcessor:该接口用于在bean的定义信息被加载后且在bean实例化前的回调
4BeanNameAware:该接口用于知道bean在IOC容器中的名字。
5BeanFactoryAware:该接口用于知道bean所在IOC容器的名字。
6PropertiesLoaderSupport:加载Properties的辅助加载类。
7PropertyResourceConfigurer:加载Property资源配置类。
8PropertyPlaceholderConfigurer:加载Property占位符配置类。
PropertiesPersister
该接口用于从流中读取和写入Property,它只有一个实现类DefaultPropertiesPersister
域
private static final boolean loadFromReaderAvailable;
private static final boolean storeToWriterAvailable;
方法
static {
//Properties是否有laod方法
loadFromReaderAvailable = ClassUtils.hasMethod(Properties.class, "load", new Class[]{Reader.class});
//Properties是否有store方法
storeToWriterAvailable = ClassUtils.hasMethod(Properties.class, "store", new Class[]{Writer.class, String.class});
}
public void load(Properties props, InputStream is) throws IOException {
props.load(is);
}
public void load(Properties props, Reader reader) throws IOException {
if (loadFromReaderAvailable) {
props.load(reader);
} else {
this.doLoad(props, reader);
}
}
//读取流中a=b或c:d,并存入props
protected void doLoad(Properties props, Reader reader) throws IOException {
//缓冲流加速读取
BufferedReader in = new BufferedReader(reader);
//
while(true) {
String line;
char firstChar;
//读取不是以#或!开头的行
do {
do {
do {
line = in.readLine();
if (line == null) {
return;
}
//去掉头部空格
line = StringUtils.trimLeadingWhitespace(line);
} while(line.length() <= 0);
firstChar = line.charAt(0);
} while(firstChar == '#');
} while(firstChar == '!');
//读完单\\后面的数据
while(this.endsWithContinuationMarker(line)) {
String nextLine = in.readLine();
line = line.substring(0, line.length() - 1);
if (nextLine != null) {
line = line + StringUtils.trimLeadingWhitespace(nextLine);
}
}
int separatorIndex = line.indexOf("=");
if (separatorIndex == -1) {
separatorIndex = line.indexOf(":");
}
String key = separatorIndex != -1 ? line.substring(0, separatorIndex) : line;
String value = separatorIndex != -1 ? line.substring(separatorIndex + 1) : "";
//去后空格
key = StringUtils.trimTrailingWhitespace(key);
//去前空格
value = StringUtils.trimLeadingWhitespace(value);
//加入props
props.put(this.unescape(key), this.unescape(value));
}
}
public void store(Properties props, OutputStream os, String header) throws IOException {
props.store(os, header);
}
public void store(Properties props, Writer writer, String header) throws IOException {
if (storeToWriterAvailable) {
props.store(writer, header);
} else {
this.doStore(props, writer, header);
}
}
//将props写入writer
protected void doStore(Properties props, Writer writer, String header) throws IOException {
BufferedWriter out = new BufferedWriter(writer);
if (header != null) {
out.write("#" + header);
out.newLine();
}
out.write("#" + new Date());
out.newLine();
Enumeration keys = props.keys();
while(keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String val = props.getProperty(key);
out.write(this.escape(key, true) + "=" + this.escape(val, false));
out.newLine();
}
out.flush();
}
//line含有单\\
protected boolean endsWithContinuationMarker(String line) {
boolean evenSlashCount = true;
for(int index = line.length() - 1; index >= 0 && line.charAt(index) == '\\'; --index) {
evenSlashCount = !evenSlashCount;
}
return !evenSlashCount;
}
PropertiesLoaderSupport
该抽象类利用PropertiesPersister完成配置文件的加载
域
public static final String XML_FILE_EXTENSION = ".xml";
private Properties[] localProperties;
private Resource[] locations;
private boolean localOverride = false;
private boolean ignoreResourceNotFound = false;
private String fileEncoding;
private PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();
方法
//若localOverride为true,则先加载配置文件到result再加载localProperties到result
//若localOverride为false,则先加载localProperties到result再加载配置文件到result
protected Properties mergeProperties() throws IOException {
Properties result = new Properties();
//读取配置文件到result
if (this.localOverride) {
this.loadProperties(result);
}
//将localProperties合并到result
if (this.localProperties != null) {
for(int i = 0; i < this.localProperties.length; ++i) {
CollectionUtils.mergePropertiesIntoMap(this.localProperties[i], result);
}
}
//
if (!this.localOverride) {
this.loadProperties(result);
}
return result;
}
//调用PropertiesPersister读取配置文件(.XML文件或者文件内容是a=b...或a:b...格式的)
protected void loadProperties(Properties props) throws IOException {
if (this.locations != null) {
for(int i = 0; i < this.locations.length; ++i) {
Resource location = this.locations[i];
if (this.logger.isInfoEnabled()) {
this.logger.info("Loading properties file from " + location);
}
InputStream is = null;
try {
is = location.getInputStream();
if (location.getFilename().endsWith(".xml")) {
this.propertiesPersister.loadFromXml(props, is);
} else if (this.fileEncoding != null) {
this.propertiesPersister.load(props, new InputStreamReader(is, this.fileEncoding));
} else {
this.propertiesPersister.load(props, is);
}
} catch (IOException var9) {
if (!this.ignoreResourceNotFound) {
throw var9;
}
if (this.logger.isWarnEnabled()) {
this.logger.warn("Could not load properties from " + location + ": " + var9.getMessage());
}
} finally {
if (is != null) {
is.close();
}
}
}
}
}
PropertyResourceConfigurer
域
public abstract class PropertyResourceConfigurer extends PropertiesLoaderSupport implements BeanFactoryPostProcessor, PriorityOrdered {
private int order = 2147483647
}
方法
//在bean定义文件加载后实例化前
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
try {
//调用从父类继承过来的mergeProperties方法
Properties mergedProps = this.mergeProperties();
//
this.convertProperties(mergedProps);
//这是个模板方法,具体由子类去实现
this.processProperties(beanFactory, mergedProps);
} catch (IOException var3) {
throw new BeanInitializationException("Could not load properties", var3);
}
}
protected void convertProperties(Properties props) {
Enumeration propertyNames = props.propertyNames();
//下面这个代码没看懂
while(propertyNames.hasMoreElements()) {
String propertyName = (String)propertyNames.nextElement();
String propertyValue = props.getProperty(propertyName);
String convertedValue = this.convertPropertyValue(propertyValue);
if (!ObjectUtils.nullSafeEquals(propertyValue, convertedValue)) {
props.setProperty(propertyName, convertedValue);
}
}
}
protected String convertPropertyValue(String originalValue) { return originalValue;}
//模板方法,由具体的子类实现
protected abstract void processProperties(ConfigurableListableBeanFactory var1, Properties var2) throws BeansException;
PropertyPlaceholderConfigurer
/*
*实现BeanNameAware和BeanFactoryAware说明PropertyPlaceholderConfigurer知道自己在容器中的名字以及所在IOC容器的名字
**/
public class PropertyPlaceholderConfigurer extends PropertyResourceConfigurer implements BeanNameAware, BeanFactoryAware {
//实现父类定义的模板方法
//
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
//新建property占位符处理器
StringValueResolver valueResolver = new PropertyPlaceholderConfigurer.PlaceholderResolvingStringValueResolver(props);
//新建beanDefinition的观察者
BeanDefinitionVisitor visitor = new BeanDefinitionVisitor(valueResolver);
//调用DefaultListableBeanFactory的getBeanDefinitionNames返回frozenBeanDefinitionNames或者beanDefinitionNames
String[] beanNames = beanFactoryToProcess.getBeanDefinitionNames();
//给其他beanDefiniton(frozenBeanDefinitionNames或者beanDefinitionNames)添加观察者,他们要是有变化我就能立马知道
for(int i = 0; i < beanNames.length; ++i) {
//不等于当前bean或者当前bean所在beanFactory
if (!beanNames[i].equals(this.beanName) || !beanFactoryToProcess.equals(this.beanFactory)) {
//获取其beanDefinition
BeanDefinition bd = beanFactoryToProcess.getBeanDefinition(beanNames[i]);
try {
//添加beanDefiniton的观察者
visitor.visitBeanDefinition(bd);
} catch (BeanDefinitionStoreException var9) {
throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanNames[i], var9.getMessage());
}
}
}
//调用SimpleAliasRegistry的resolveAliases方法,即别名处理
beanFactoryToProcess.resolveAliases(valueResolver);
}
//获取${(${})*}中最后一个}的索引
private int findPlaceholderEndIndex(CharSequence buf, int startIndex) {
int index = startIndex + this.placeholderPrefix.length();
int withinNestedPlaceholder = 0;
while(index < buf.length()) {
if (StringUtils.substringMatch(buf, index, this.placeholderSuffix)) {
if (withinNestedPlaceholder <= 0) {
return index;
}
//嵌套减一层
--withinNestedPlaceholder;
index += this.placeholderSuffix.length();
} else if (StringUtils.substringMatch(buf, index, this.placeholderPrefix)) {
//嵌套加一层
++withinNestedPlaceholder;
index += this.placeholderPrefix.length();
} else {
++index;
}
}
return -1;
}
//替换占位符的值
protected String resolvePlaceholder(String placeholder, Properties props, int systemPropertiesMode) {
String propVal = null;
//如果systemPropertiesMode==2从System中获取placeholder的值
if (systemPropertiesMode == 2) {propVal = this.resolveSystemProperty(placeholder);}
//再从props中获取placeholder的值
if (propVal == null) { propVal = this.resolvePlaceholder(placeholder, props);}
//如果systemPropertiesMode==1从System中获取placeholder的值
if (propVal == null && systemPropertiesMode == 1) {propVal = this.resolveSystemProperty(placeholder);}
return propVal;
}
//返回props中placeholder的值
protected String resolvePlaceholder(String placeholder, Properties props) {
return props.getProperty(placeholder);
}
//返回System.getProperty(key)或者System.getenv(key);
protected String resolveSystemProperty(String key) {
try {
String value = System.getProperty(key);
if (value == null && this.searchSystemEnvironment) { value = System.getenv(key); }
return value;
} catch (Throwable var3) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Could not access system property '" + key + "': " + var3);
}
return null;
}
}
//将strVal中是${(${)*\w+(})*}格式且\w+的key存在在props替换成对应的值
protected String parseStringValue(String strVal, Properties props, Set visitedPlaceholders) throws BeanDefinitionStoreException {
StringBuffer buf = new StringBuffer(strVal);
int startIndex = strVal.indexOf(this.placeholderPrefix);
while(startIndex != -1) {
int endIndex = this.findPlaceholderEndIndex(buf, startIndex);
if (endIndex != -1) {
String placeholder = buf.substring(startIndex + this.placeholderPrefix.length(), endIndex);
if (!visitedPlaceholders.add(placeholder)) {
throw new BeanDefinitionStoreException("Circular placeholder reference '" + placeholder + "' in property definitions");
}
placeholder = this.parseStringValue(placeholder, props, visitedPlaceholders);
String propVal = this.resolvePlaceholder(placeholder, props, this.systemPropertiesMode);
if (propVal != null) {
propVal = this.parseStringValue(propVal, props, visitedPlaceholders);
buf.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal);
if (this.logger.isTraceEnabled()) {
this.logger.trace("Resolved placeholder '" + placeholder + "'");
}
startIndex = buf.indexOf(this.placeholderPrefix, startIndex + propVal.length());
} else {
if (!this.ignoreUnresolvablePlaceholders) {
throw new BeanDefinitionStoreException("Could not resolve placeholder '" + placeholder + "'");
}
startIndex = buf.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());
}
visitedPlaceholders.remove(placeholder);
} else {
startIndex = -1;
}
}
return buf.toString();
}
private class PlaceholderResolvingStringValueResolver implements StringValueResolver {
private final Properties props;
public PlaceholderResolvingStringValueResolver(Properties props) { this.props = props; }
//返回null或者替换占位符后的字符串
public String resolveStringValue(String strVal) throws BeansException {
//替换strVal中${]占位符的值
String value = PropertyPlaceholderConfigurer.this.parseStringValue(strVal, this.props, new HashSet());
//
return value.equals(PropertyPlaceholderConfigurer.this.nullValue) ? null : value;
}
}
}
总结
1PropertiesPersister是完成配置文件加载的工具类。
2PropertiesLoaderSupport是利用工具PropertiesPersister完成配置文件的加载。
3PropertyResourceConfigurer在PropertiesLoaderSupport的基础上实现了BeanFactoryPostProcessor, PriorityOrdered,增加了order权重和定义文件加载后实例化前的postProcessBeanFactory方法,该方法定义了一个模板方法processProperties,由子类实现
4PropertyPlaceholderConfigurer实现了processProperties方法,该实现方法给其他bean或者其他容器的bean添加观察者监视他们的beanDefinition变化,接着注册别名。