IOC的基础
下面咱们从IOC/AOP开始,它们是Spring平台实现的核心部分;虽然,咱们一开始大多只是在这个层面上,作一些配置和外部特性的使用工 做,但对这两个核心模块工做原理和运做机制的理解,对深刻理解Spring平台,倒是相当重要的;由于,它们同时也是Spring其余模块实现的基础。从 Spring要作到的目标,也就是从简化Java EE开发的出发点来看,简单的来讲,它是经过对POJO开发的支持,来具体实现的;具体的说,Spring经过为应用开发提供基于POJO的开发模式,把 应用开发和复杂的Java EE服务,实现解耦,并经过提升单元测试的覆盖率,从而有效的提升整个应用的开发质量。这样一来,实际上,就须要把为POJO提供支持的,各类Java EE服务支持抽象到应用平台中去,去封装起来;而这种封装功能的实现,在Spring中,就是由IOC容器以及AOP来具体提供的,这两个模块,在很大程 度上,体现了Spring做为应用开发平台的核心价值。它们的实现,是Rod.Johnson在他的另外一本著做《Expert One-on-One J2EE Development without EJB》 中,所提到Without EJB设计思想的体现;同时也深入的体现了Spring背后的设计理念。
从更深一点的技术层面上来看,由于Spring是一个基于Java语言的应用平台,若是咱们可以对Java计算模型,好比像JVM虚拟机实现技术 的基本原理有一些了解,会让咱们对Spring实现的理解,更加的深刻,这些JVM虚拟机的特性使用,包括像反射机制,代理类,字节码技术等等。它们都是 在Spring实现中,涉及到的一些Java计算环境的底层技术;尽管对应用开发人员来讲,可能不会直接去涉及这些JVM虚拟机底层实现的工做,可是了解 这些背景知识,或多或少,对咱们了解整个Spring平台的应用背景有很大的帮助;打个比方来讲,就像咱们在大学中,学习的那些关于计算机组织和系统方面 的基本知识,好比像数字电路,计算机组成原理,汇编语言,操做系统等等这些基本课程的学习。虽然,坦率的来讲,对咱们这些大多数课程的学习者,在之后的工 做中,可能并无太多的机会,直接从事这么如此底层的技术开发工做;但具有这些知识背景,为咱们深刻理解基于这些基础技术构架起来的应用系统,毫无疑问, 是不可缺乏的。随着JVM虚拟机技术的发展,能够设想到的是,更多虚拟机级别的基本特性,将会持续的被应用平台开发者所关注和采用,这也是咱们在学习平台 实现的过程当中,很是值得注意的一点,由于这些底层技术实现,毫无疑问,会对Spring应用平台的开发路线,产品策略产生重大的影响。同时,在使用 Spring做为应用平台的时候,若是须要更深层次的开发和性能调优,这些底层的知识,也是咱们知识库中不可缺乏的部分。有了这些底层知识,理解整个系 统,想来就应该障碍不大了。
IOC的一点认识
对Spring IOC的理解离不开对依赖反转模式的理解,咱们知道,关于如何反转对依赖的控制,把控制权从具体业务对象手中转交到平台或者框架中,是解决面向对象系统设 计复杂性和提升面向对象系统可测试性的一个有效的解决方案。这个问题触发了IoC设计模式的发展,是IoC容器要解决的核心问题。同时,也是产品化的 IoC容器出现的推进力。而我以为Spring的IoC容器,就是一个开源的实现依赖反转模式的产品。
那具体什么是IoC容器呢?它在Spring框架中到底长什么样?说了这么多,其实对IoC容器的使用者来讲,咱们经常接触到的 BeanFactory和ApplicationContext均可以当作是容器的具体表现形式。这些就是IoC容器,或者说在Spring中提IoC容 器,从实现来讲,指的是一个容器系列。这也就是说,咱们一般所说的IoC容器,若是深刻到Spring的实现去看,会发现IoC容器实际上表明着一系列功 能各异的容器产品。只是容器的功能有大有小,有各自的特色。打个比方来讲,就像是百货商店里出售的商品,咱们举水桶为例子,在商店中出售的水桶有大有小; 制做材料也各不相同,有金属的,有塑料的等等,总之是各式各样,但只要能装水,具有水桶的基本特性,那就能够做为水桶来出售来让用户使用。这在 Spring中也是同样,它有各式各样的IoC容器的实现供用户选择和使用;使用什么样的容器彻底取决于用户的须要,但在使用以前若是可以了解容器的基本 状况,那会对容器的使用是很是有帮助的;就像咱们在购买商品时进行的对商品的考察和挑选那样。
咱们从最基本的XmlBeanFactory看起,它是容器系列的最底层实现,这个容器的实现与咱们在Spring应用中用到的那些上下文相比, 有一个很是明显的特色,它只提供了最基本的IoC容器的功能。从它的名字中能够看出,这个IoC容器能够读取以XML形式定义的 BeanDefinition。理解这一点有助于咱们理解ApplicationContext与基本的BeanFactory之间的区别和联系。咱们可 以认为直接的BeanFactory实现是IoC容器的基本形式,而各类ApplicationContext的实现是IoC容器的高级表现形式。
仔细阅读XmlBeanFactory的源码,在一开始的注释里面已经对 XmlBeanFactory的功能作了简要的说明,从代码的注释还能够看到,这是Rod Johnson在2001年就写下的代码,可见这个类应该是Spring的元老类了。它是继承DefaultListableBeanFactory这个 类的,这个DefaultListableBeanFactory就是一个很值得注意的容器!
node
public class XmlBeanFactory extends DefaultListableBeanFactory { 网络
private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this); 数据结构
public XmlBeanFactory(Resource resource) throws BeansException { 框架
this(resource, null); ide
} 性能
public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException { 单元测试
super(parentBeanFactory); 学习
this.reader.loadBeanDefinitions(resource); 测试
}
}
XmlBeanFactory的功能是创建在DefaultListableBeanFactory这个基本容器的基础上的,在这个基本容器的基 础上实现了其余诸如XML读取的附加功能。对于这些功能的实现原理,看一看XmlBeanFactory的代码实现就能很容易地理解。在以下的代码中能够 看到,在XmlBeanFactory构造方法中须要获得Resource对象。对XmlBeanDefinitionReader对象的初始化,以及使 用这个这个对象来完成loadBeanDefinitions的调用,就是这个调用启动了从Resource中载入BeanDefinitions的过 程,这个loadBeanDefinitions同时也是IoC容器初始化的重要组成部分。
简单来讲,IoC容器的初始化包括BeanDefinition的Resouce定位、载入和注册这三个基本的过程。我以为重点是在载入和对 BeanDefinition作解析的这个过程。能够从DefaultListableBeanFactory来入手看看IoC容器是怎样完成 BeanDefinition载入的。在refresh调用完成之后,能够看到loadDefinition的调用:
public abstract class AbstractXmlApplicationContext extends AbstractRefreshableConfigApplicationContext {
public AbstractXmlApplicationContext() {
}
public AbstractXmlApplicationContext(ApplicationContext parent) {
super(parent);
}
//这里是实现loadBeanDefinitions的地方
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
// 建立 XmlBeanDefinitionReader,并经过回调设置到 BeanFactory中去,建立BeanFactory的使用的也是 DefaultListableBeanFactory。
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
// 这里设置 XmlBeanDefinitionReader, 为XmlBeanDefinitionReader 配置ResourceLoader,由于DefaultResourceLoader是父类,因此this能够直接被使用
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
// 这是启动Bean定义信息载入的过程
initBeanDefinitionReader(beanDefinitionReader);
loadBeanDefinitions(beanDefinitionReader);
}
protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) {
}
这里使用 XmlBeanDefinitionReader来载入BeanDefinition到容器中,如如下代码清单所示:
//这里是调用的入口。
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
}
//这里是载入XML形式的BeanDefinition的地方。
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isInfoEnabled()) {
logger.info("Loading XML bean definitions from " + encodedResource.getResource());
}
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
currentResources = new HashSet<EncodedResource>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected recursive loading of " + encodedResource + " - check your import definitions!");
}
//这里获得XML文件,并获得IO的InputSource准备进行读取。
try {
InputStream inputStream = encodedResource.getResource().getInputStream();
try {
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
finally {
inputStream.close();
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"IOException parsing XML document from " + encodedResource.getResource(), ex);
}
finally {
currentResources.remove(encodedResource);
if (currentResources.isEmpty()) {
this.resourcesCurrentlyBeingLoaded.set(null);
}
}
}
//具体的读取过程能够在doLoadBeanDefinitions方法中找到:
//这是从特定的XML文件中实际载入BeanDefinition的地方
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
int validationMode = getValidationModeForResource(resource);
//这里取得XML文件的Document对象,这个解析过程是由 documentLoader完成的,这个documentLoader是DefaultDocumentLoader,在定义documentLoader的地方建立
Document doc = this.documentLoader.loadDocument(
inputSource, getEntityResolver(), this.errorHandler, validationMode, isNamespaceAware());
//这里启动的是对BeanDefinition解析的详细过程,这个解析会使用到Spring的Bean配置规则,是咱们下面须要详细关注的地方。
return registerBeanDefinitions(doc, resource);
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (SAXParseException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
}
catch (SAXException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"XML document from " + resource + " is invalid", ex);
}
catch (ParserConfigurationException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Parser configuration exception parsing XML from " + resource, ex);
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"IOException parsing XML document from " + resource, ex);
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Unexpected exception parsing XML document from " + resource, ex);
}
}
关于具体的Spring BeanDefinition的解析,是在BeanDefinitionParserDelegate中完成的。这个类里包含了各类Spring Bean定义规则的处理,感兴趣的同窗能够仔细研究。咱们举一个例子来分析这个处理过程,好比咱们最熟悉的对Bean元素的处理是怎样完成的,也就是咱们 在XML定义文件中出现的<bean></bean>这个最多见的元素信息是怎样被处理的。在这里,咱们会看到那些熟悉的 BeanDefinition定义的处理,好比id、name、aliase等属性元素。把这些元素的值从XML文件相应的元素的属性中读取出来之后,会 被设置到生成的BeanDefinitionHolder中去。这些属性的解析仍是比较简单的。对于其余元素配置的解析,好比各类Bean的属性配置,通 过一个较为复杂的解析过程,这个过程是由parseBeanDefinitionElement来完成的。解析完成之后,会把解析结果放到 BeanDefinition对象中并设置到BeanDefinitionHolder中去,如如下清单所示:
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
//这里取得在<bean>元素中定义的id、name和aliase属性的值
String id = ele.getAttribute(ID_ATTRIBUTE);
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
List<String> aliases = new ArrayList<String>();
if (StringUtils.hasLength(nameAttr)) {
String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, BEAN_NAME_DELIMITERS);
aliases.addAll(Arrays.asList(nameArr));
}
String beanName = id;
if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
beanName = aliases.remove(0);
if (logger.isDebugEnabled()) {
logger.debug("No XML 'id' specified - using '" + beanName +
"' as bean name and " + aliases + " as aliases");
}
}
if (containingBean == null) {
checkNameUniqueness(beanName, aliases, ele);
}
//这个方法会引起对bean元素的详细解析
AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
if (beanDefinition != null) {
if (!StringUtils.hasText(beanName)) {
try {
if (containingBean != null) {
beanName = BeanDefinitionReaderUtils.generateBeanName(
beanDefinition, this.readerContext.getRegistry(), true);
}
else {
beanName = this.readerContext.generateBeanName(beanDefinition);
// Register an alias for the plain bean class name, if still possible,
// if the generator returned the class name plus a suffix.
// This is expected for Spring 1.2/2.0 backwards compatibility.
String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null &&
beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
aliases.add(beanClassName);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Neither XML 'id' nor 'name' specified - " +
"using generated bean name [" + beanName + "]");
}
}
catch (Exception ex) {
error(ex.getMessage(), ele);
return null;
}
}
String[] aliasesArray = StringUtils.toStringArray(aliases);
return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
}
return null;
}
在具体生成BeanDefinition之后。咱们举一个对property进行解析的例子来完成对整个BeanDefinition载入过程的 分析,仍是在类BeanDefinitionParserDelegate的代码中,它对BeanDefinition中的定义一层一层地进行解析,好比 从属性元素集合到具体的每个属性元素,而后才是对具体的属性值的处理。根据解析结果,对这些属性值的处理会封装成PropertyValue对象并设置 到BeanDefinition对象中去,如如下代码清单所示。
/**
* 这里对指定bean元素的property子元素集合进行解析。
*/
public void parsePropertyElements(Element beanEle, BeanDefinition bd) {
//遍历全部bean元素下定义的property元素
NodeList nl = beanEle.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element && DomUtils.nodeNameEquals(node, PROPERTY_ELEMENT)) {
//在判断是property元素后对该property元素进行解析的过程
parsePropertyElement((Element) node, bd);
}
}
}
public void parsePropertyElement(Element ele, BeanDefinition bd) {
//这里取得property的名字
String propertyName = ele.getAttribute(NAME_ATTRIBUTE);
if (!StringUtils.hasLength(propertyName)) {
error("Tag 'property' must have a 'name' attribute", ele);
return;
}
this.parseState.push(new PropertyEntry(propertyName));
try {
//若是同一个bean中已经有同名的存在,则不进行解析,直接返回。也就是说,若是在同一个bean中有同名的property设置,那么起做用的只是第一个。
if (bd.getPropertyValues().contains(propertyName)) {
error("Multiple 'property' definitions for property '" + propertyName + "'", ele);
return;
}
//这里是解析property值的地方,返回的对象对应对Bean定义的property属性设置的解析结果,这个解析结果会封装到PropertyValue对象中,而后设置到BeanDefinitionHolder中去。
Object val = parsePropertyValue(ele, bd, propertyName);
PropertyValue pv = new PropertyValue(propertyName, val);
parseMetaElements(ele, pv);
pv.setSource(extractSource(ele));
bd.getPropertyValues().addPropertyValue(pv);
}
finally {
this.parseState.pop();
}
}
/**
* 这里取得property元素的值,也许是一个list或其余。
*/
public Object parsePropertyValue(Element ele, BeanDefinition bd, String propertyName) {
String elementName = (propertyName != null) ?
"<property> element for property '" + propertyName + "'" :
"<constructor-arg> element";
// Should only have one child element: ref, value, list, etc.
NodeList nl = ele.getChildNodes();
Element subElement = null;
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element && !DomUtils.nodeNameEquals(node, DESCRIPTION_ELEMENT) &&
!DomUtils.nodeNameEquals(node, META_ELEMENT)) {
// Child element is what we're looking for.
if (subElement != null) {
error(elementName + " must not contain more than one sub-element", ele);
}
else {
subElement = (Element) node;
}
}
}
//这里判断property的属性,是ref仍是value,不容许同时是ref和value。
boolean hasRefAttribute = ele.hasAttribute(REF_ATTRIBUTE);
boolean hasValueAttribute = ele.hasAttribute(VALUE_ATTRIBUTE);
if ((hasRefAttribute && hasValueAttribute) ||
((hasRefAttribute || hasValueAttribute) && subElement != null)) {
error(elementName +
" is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele);
}
//若是是ref,建立一个ref的数据对象RuntimeBeanReference,这个对象封装了ref的信息。
if (hasRefAttribute) {
String refName = ele.getAttribute(REF_ATTRIBUTE);
if (!StringUtils.hasText(refName)) {
error(elementName + " contains empty 'ref' attribute", ele);
}
RuntimeBeanReference ref = new RuntimeBeanReference(refName);
ref.setSource(extractSource(ele));
return ref;
} //若是是value,建立一个value的数据对象TypedStringValue ,这个对象封装了value的信息。
else if (hasValueAttribute) {
TypedStringValue valueHolder = new TypedStringValue(ele.getAttribute(VALUE_ATTRIBUTE));
valueHolder.setSource(extractSource(ele));
return valueHolder;
} //若是还有子元素,触发对子元素的解析
else if (subElement != null) {
return parsePropertySubElement(subElement, bd);
}
else {
// Neither child element nor "ref" or "value" attribute found.
error(elementName + " must specify a ref or value", ele);
return null;
}
}
好比,再往下看,咱们看到像List这样的属性配置是怎样被解析的,依然在BeanDefinitionParserDelegate中:返回的 是一个List对象,这个List是Spring定义的ManagedList,做为封装List这类配置定义的数据封装,如如下代码清单所示。
public List parseListElement(Element collectionEle, BeanDefinition bd) {
String defaultElementType = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE);
NodeList nl = collectionEle.getChildNodes();
ManagedList<Object> target = new ManagedList<Object>(nl.getLength());
target.setSource(extractSource(collectionEle));
target.setElementTypeName(defaultElementType);
target.setMergeEnabled(parseMergeAttribute(collectionEle));
//具体的List元素的解析过程。
parseCollectionElements(nl, target, bd, defaultElementType);
return target;
}
protected void parseCollectionElements(
NodeList elementNodes, Collection<Object> target, BeanDefinition bd, String defaultElementType) {
//遍历全部的元素节点,并判断其类型是否为Element。
for (int i = 0; i < elementNodes.getLength(); i++) {
Node node = elementNodes.item(i);
if (node instanceof Element && !DomUtils.nodeNameEquals(node, DESCRIPTION_ELEMENT)) {
//加入到target中去,target是一个ManagedList,同时触发对下一层子元素的解析过程,这是一个递归的调用。
target.add(parsePropertySubElement((Element) node, bd, defaultElementType));
}
}
}
通过这样一层一层的解析,咱们在XML文件中定义的BeanDefinition就被整个给载入到了IoC容器中,并在容器中创建了数据映射。在 IoC容器中创建了对应的数据结构,或者说能够当作是POJO对象在IoC容器中的映像,这些数据结构能够以 AbstractBeanDefinition为入口,让IoC容器执行索引、查询和操做。在个人感受中,对核心数据结构的定义和处理应该能够当作是一个软件的核心部分了。因此,这里的BeanDefinition的载入能够说是IoC容器的核心,若是说IoC容器是Spring的核心,那么这些BeanDefinition就是Spring的核心的核心了!呵呵,这部分代码数量不小,但若是掌握这条主线,其余均可以触类旁通吧,就像咱们掌握了操做系统启动的过程,以及在操做系统设计中的核心数据结构 像进程数据结构,文件系统数据结构,网络协议数据结构的设计和处理同样,对整个系统的设计原理,包括移植,驱动开发和应用开发,是很是有帮助的!