Spring源码-入门

一、测试类

  public class Main {
  public static void main(String[] args) {
	ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:app-${user}.xml");
	Person person = applicationContext.getBean(Person.class);
	System.out.println(person.getName());
 }
 }

同时添加jvm参数-Duser=test

二、app-test.xml文件

<beans>
	<bean id="person" class="xml.Person">
		<property value="张三" name="name"></property>
	</bean>
</beans>

三、源码跟踪

public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
	this(new String[] {configLocation}, true, null);
}

创建ClassPathXmlApplicationContext从xml位置加载Bean定义。

public ClassPathXmlApplicationContext(
		String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
		throws BeansException {
	super(parent); // 初始化父类
	setConfigLocations(configLocations); // 设置xml文件位置
	if (refresh) {
		refresh(); // 刷新容器
	}
}

从super(parent);进去

public AbstractApplicationContext(@Nullable ApplicationContext parent) {
	this();
	setParent(parent);
}

	@Override
public void setParent(@Nullable ApplicationContext parent) {
	this.parent = parent;
	if (parent != null) {
		Environment parentEnvironment = parent.getEnvironment();
		if (parentEnvironment instanceof ConfigurableEnvironment) {
			getEnvironment().merge((ConfigurableEnvironment) parentEnvironment);  // 与父类的Environment对象合并
		}
	}
}


public void setConfigLocations(@Nullable String... locations) {
	if (locations != null) {
		Assert.noNullElements(locations, "Config locations must not be null");
		this.configLocations = new String[locations.length];
		for (int i = 0; i < locations.length; i++) {
			this.configLocations[i] = resolvePath(locations[i]).trim();   // 解析xml文件的路径,xml文件路径可能存在${}的情况,需要解析替换
		}
	}
	else {
		this.configLocations = null;
	}
}

    protected String resolvePath(String path) {
	return getEnvironment().resolveRequiredPlaceholders(path); // 解析${...}并替换
}

    	@Override
public ConfigurableEnvironment getEnvironment() {
	if (this.environment == null) {
		this.environment = createEnvironment();
	}
	return this.environment;
}

    protected ConfigurableEnvironment createEnvironment() {
	return new StandardEnvironment();
}

查看StandardEnvironment的父类AbstractEnvironment构造函数

    public AbstractEnvironment() {
	this(new MutablePropertySources());
}

    protected AbstractEnvironment(MutablePropertySources propertySources) {
	this.propertySources = propertySources;
	this.propertyResolver = createPropertyResolver(propertySources);
	customizePropertySources(propertySources);
}

    protected void customizePropertySources(MutablePropertySources propertySources) {
}

StandardEnvironment的customizePropertySources方法

    	@Override
protected void customizePropertySources(MutablePropertySources propertySources) {
	propertySources.addLast(
			new PropertiesPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties()));
	propertySources.addLast(
			new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment()));
}

AbstractEnvironment类

    @Override
@SuppressWarnings({"rawtypes", "unchecked"})
public Map<String, Object> getSystemProperties() {
	try {
		return (Map) System.getProperties(); // 获取JVM属性
	}
	catch (AccessControlException ex) {
		return (Map) new ReadOnlySystemAttributesMap() {
			@Override
			@Nullable
			protected String getSystemAttribute(String attributeName) {
				try {
					return System.getProperty(attributeName);
				}
				catch (AccessControlException ex) {
					if (logger.isInfoEnabled()) {
						logger.info("Caught AccessControlException when accessing system property '" +
								attributeName + "'; its value will be returned [null]. Reason: " + ex.getMessage());
					}
					return null;
				}
			}
		};
	}
}

    	@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public Map<String, Object> getSystemEnvironment() {
	if (suppressGetenvAccess()) {
		return Collections.emptyMap();
	}
	try {
		return (Map) System.getenv(); // 获取系统设置的属性
	}
	catch (AccessControlException ex) {
		return (Map) new ReadOnlySystemAttributesMap() {
			@Override
			@Nullable
			protected String getSystemAttribute(String attributeName) {
				try {
					return System.getenv(attributeName);
				}
				catch (AccessControlException ex) {
					if (logger.isInfoEnabled()) {
						logger.info("Caught AccessControlException when accessing system environment variable '" +
								attributeName + "'; its value will be returned [null]. Reason: " + ex.getMessage());
					}
					return null;
				}
			}
		};
	}
}

resolveRequiredPlaceholders

     //AbstractEnvironment
    	@Override
public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
	return this.propertyResolver.resolveRequiredPlaceholders(text);  \\ propertyResolver是PropertySourcesPropertyResolver
}

在创建StandardEnvironment对象时

    public AbstractEnvironment() {
	this(new MutablePropertySources());
}

    protected AbstractEnvironment(MutablePropertySources propertySources) {
	this.propertySources = propertySources;
	this.propertyResolver = createPropertyResolver(propertySources);
	customizePropertySources(propertySources);
}


    protected ConfigurablePropertyResolver createPropertyResolver(MutablePropertySources propertySources) {
	return new PropertySourcesPropertyResolver(propertySources);
}

PropertySourcesPropertyResolver的父类AbstractPropertyResolver的方法resolveRequiredPlaceholders

    @Override
public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
	if (this.strictHelper == null) {
		this.strictHelper = createPlaceholderHelper(false);
	}
	return doResolvePlaceholders(text, this.strictHelper);
}

    private String doResolvePlaceholders(String text, PropertyPlaceholderHelper helper) {
	return helper.replacePlaceholders(text, this::getPropertyAsRawString);
}

    public String replacePlaceholders(String value, PlaceholderResolver placeholderResolver) {
	Assert.notNull(value, "'value' must not be null");
	return parseStringValue(value, placeholderResolver, null);
}

    protected String parseStringValue(
		String value, PlaceholderResolver placeholderResolver, @Nullable Set<String> visitedPlaceholders) {

	int startIndex = value.indexOf(this.placeholderPrefix); //placeholderPrefix = "${"; 查找前缀位置
	if (startIndex == -1) {
		return value;
	}

	StringBuilder result = new StringBuilder(value);
	while (startIndex != -1) {
		int endIndex = findPlaceholderEndIndex(result, startIndex); // 从startIndex开始在result查找placeholderSuffix的位置
		if (endIndex != -1) {
			String placeholder = result.substring(startIndex + this.placeholderPrefix.length(), endIndex);  
			String originalPlaceholder = placeholder;
			if (visitedPlaceholders == null) {
				visitedPlaceholders = new HashSet<>(4);
			}
			if (!visitedPlaceholders.add(originalPlaceholder)) {
				throw new IllegalArgumentException(
						"Circular placeholder reference '" + originalPlaceholder + "' in property definitions");
			}
			// Recursive invocation, parsing placeholders contained in the placeholder key.
			placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders); //递归调用parseStringValue解析placeholder,${}里面可能存在${}
			// Now obtain the value for the fully resolved key...
			String propVal = placeholderResolver.resolvePlaceholder(placeholder); //通过系统属性解析placeholder
			if (propVal == null && this.valueSeparator != null) { // 设置默认值
				int separatorIndex = placeholder.indexOf(this.valueSeparator);
				if (separatorIndex != -1) {
					String actualPlaceholder = placeholder.substring(0, separatorIndex);
					String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length());
					propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder);
					if (propVal == null) {
						propVal = defaultValue;
					}
				}
			}
			if (propVal != null) {
				// Recursive invocation, parsing placeholders contained in the
				// previously resolved placeholder value.
				propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders);
				result.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal);
				if (logger.isTraceEnabled()) {
					logger.trace("Resolved placeholder '" + placeholder + "'");
				}
				startIndex = result.indexOf(this.placeholderPrefix, startIndex + propVal.length());
			}
			else if (this.ignoreUnresolvablePlaceholders) {
				// Proceed with unprocessed value.
				startIndex = result.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());
			}
			else {
				throw new IllegalArgumentException("Could not resolve placeholder '" +
						placeholder + "'" + " in value \"" + value + "\"");
			}
			visitedPlaceholders.remove(originalPlaceholder);
		}
		else {
			startIndex = -1;
		}
	}
	return result.toString();
}

   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)) { // placeholderSuffix = "}"
			if (withinNestedPlaceholder > 0) {
				withinNestedPlaceholder--;
				index = index + this.placeholderSuffix.length();
			}
			else {
				return index;
			}
		}
		else if (StringUtils.substringMatch(buf, index, this.simplePrefix)) {
			withinNestedPlaceholder++;
			index = index + this.simplePrefix.length();
		}
		else {
			index++;
		}
	}
	return -1;
}
posted @ 2022-08-20 15:17  shigp1  阅读(32)  评论(0编辑  收藏  举报