Spring技术内幕——深入解析Spring架构与设计原理(一)IOC实现原理
转自:http://www.javaeye.com/topic/493282?page=1
简单来说,自己的软件产品是一个基于互联网的SaaS协同软件平台,操作简单,支持流程定义,管理和多种客户端 -像短信,MSN,智能手机什么的(我这里就不多做什么广告了),也有一个企业版的版本,使用的技术框架是hibernate + Spring + Wicket,下面是Linux和MySQL,还有云计算的平台的使用,以支持其扩展性,虽然现在还没有可扩展性的需求,但似乎不难从SaaS上,就会想到云计算, 其实,它们真的是天生的一对!
关于云计算,自己对这个技术很感兴趣,觉得和开源软件的结合,是很有意思的,因为它们都有基于服务的基因,在云计算平台的使用上,也有一些初步的实践。云计算是一个很有意思的话题,但在这里主要是想谈Spring,所以对云计算,这里就先不多说了,但非常欢迎有兴趣的朋友和一起另外找地方讨论!
回到正题,在我自己的产品中,其中除了Wicket和云计算外,其他都是大家非常熟知的了,像Hibernate, Spring, MySQL什么的。在这个过程中,发现自己对一些技术点也有了新的认识,最有体会的是Spring。当然,在这个过程中,更大的收获是对产品开发整个过程的认识,在这点上,真是一言难尽........
回到自己还算了解的Spring, 这次我使用的是3.0的代码,所以,有机会也把这些代码读了几遍,比原来的理解要加深了许多,也发现了不少和2.0代码不同的地方,以及自己一些对 Spring的新的理解,这些,就让我就用这个帖子系列,给自己总结一下,也算是对自己以前的那个代码分析的帖子做一个新的交代吧。
自己对Spring一点小小的见解
简化Java企业应用的开发,是Spring框架的目标.就是我们熟知的当年的那个interface21,也亦非吴下阿蒙了,由它演进出来的Spring,以及由它带来的崭新开发理念,也早已伴随着这个开源框架的广泛应用,而飞入寻常百姓家。与此同时,伴随着Spring的成熟,开源社区的成长,在Rod.Johnson的领导下,以Spring为核心的一系列开源软件的产品组合,其脉络也逐渐的清晰和丰富起来;现在,已经发展成为一个包括软件运行,构建,部署运营,从而涵盖整个软件服务生命周期的产品族群;同时也成为,在当今主流的软件业态中,一个不可或缺的重要组成。
在最近完成的VMware公司对Spring的运营者SpringSource公司的收购中,也让我们又看到了一个,在开源软件中,蕴含着的巨大商业价值,以及又一次基于开源模式的商业成功;也让我们看到,Spring为自己设计的未来定位,它与云计算的融合趋势,以及,努力成为在云计算业态中,PaaS(Platform As a Service)服务有力竞争者的战略设想;由此,可以想象,在云计算这个全新的计算时代中,如何秉承Spring的一贯风格,为云计算应用的开发,提供高可靠,高可用,高可扩展,高性能的应用平台,对Spring团队来说,是一个面临的全新挑战;在这个领域中的雄心和今后的作为,那就让我们一起拭目以待吧。这里也有点凑巧了,正好Spring和云计算都是自己喜欢的东西,说不定以后,我还能够在这两者的结合上再写些东西呢。
作为一个庞大的体系,Spring在Java企业应用中, 和我们熟悉的企业应用服务器一样,比如我们熟知的其他产品,像Weblogic,Websphere,JBoss,.NET这些等等,其定位和目的,都在于希望能够起到一个企业应用资源的集成管理,以及为应用开发提供平台支持的作用,这和我们熟知的,像UNIX和Windows这样传统意义上的操作系统,在传统的计算系统中,起到的作用非常的类似。只不过,按照个人的理解,它们不同在于,我们熟知的传统操作系统关心的是存储,计算,通信,外围设备这些物理资源的管理,并在管理这些资源的基础上,为应用程序提供一个统一平台和服务接口;而像Spring这样的应用平台,它们关心的是在Java企业应用中,对包括那些像Web应用,数据持久化,事务处理,消息中间件,分布式计算等等这些,为企业应用服务的抽象资源的统一管理,并在此基础上,为应用提供一个基于 POJO的开发环境。尽管各自面向的资源,管理的对象,支持的应用以及使用的场景不同,但这两者在整个系统中的定位,却依然有着可以类比和相互参考的地方,从某种意义上看,它们都起到一个资源协调,平台支持,以及服务集成的作用。
所以我觉得可以使用,我们看待传统操作系统的方法和一些基本观念,来对Spring进行系统分析,以及对Spring进行层次划分,这样可能更加容易理解,同时,所以,个人感觉,仿照传统操作系统的眼光,把对Spring框架的实现,划分为核心,组件和应用这三个基本的层次,来理解Spring框架是不错的一个方法,就算是众所周知的“三段论”的应用吧。不知道这种分析方法,是不是太庸俗,但我自己还是觉得挺受用的,呵呵,谁叫我是个俗人呢!
今天先写一些,就算是起个头吧,明天继续! 写写IOC/AOP的一些具体东西。
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就是一个很值得注意的容器!
- public class XmlBeanFactory extends DefaultListableBeanFactory {
- private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);
- public XmlBeanFactory(Resource resource) throws BeansException {
- this(resource, null);
- }
- public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
- super(parentBeanFactory);
- this.reader.loadBeanDefinitions(resource);
- }
- }
- public class XmlBeanFactory extends DefaultListableBeanFactory {
- private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);
- public XmlBeanFactory(Resource resource) throws BeansException {
- this(resource, null);
- }
- 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) {
- }
- 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
currentResources = this.resourcesCurrentlyBeingLoaded.get(); - if (currentResources == null) {
- currentResources = new HashSet
( 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);
- }
- }
- //这里是调用的入口。
- 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
currentResources = this.resourcesCurrentlyBeingLoaded.get(); - if (currentResources == null) {
- currentResources = new HashSet
( 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定义文件中出现的
- public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
- //这里取得在
元素中定义的id、name和aliase属性的值 - String id = ele.getAttribute(ID_ATTRIBUTE);
- String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
- List
aliases = new ArrayList(); - 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;
- }
- public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
- //这里取得在
元素中定义的id、name和aliase属性的值 - String id = ele.getAttribute(ID_ATTRIBUTE);
- String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
- List
aliases = new ArrayList (); - 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) ?
- "
element for property '" + propertyName + "'" : - "
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;
- }
- }
- /**
- * 这里对指定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) ?
- "
element for property '" + propertyName + "'" : - "
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();
- ManagedListnew ManagedList
- 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
- //遍历所有的元素节点,并判断其类型是否为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));
- }
- }
- }
- public List parseListElement(Element collectionEle, BeanDefinition bd) {
- String defaultElementType = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE);
- NodeList nl = collectionEle.getChildNodes();
- ManagedList
- 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
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的核心的核心了!
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
