Spring ~ 设计模式。

Spring ~ 设计模式。



Spring 基本使用。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.geek</groupId>
    <artifactId>spring-geek</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
    </dependencies>

</project>

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="userDao" class="com.geek.dao.impl.UserDaoImpl"/>

    <bean id="userService" class="com.geek.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"/>
    </bean>

</beans>

package com.geek.dao;

/**
 * @author geek
 */
public interface IUserDao {

    void add();

}

package com.geek.dao.impl;

import com.geek.dao.IUserDao;

/**
 * @author geek
 */
public class UserDaoImpl implements IUserDao {

    @Override
    public void add() {
        System.out.println("userDao ~ add();");
    }

}

package com.geek.service;

/**
 * @author geek
 */
public interface IUserService {

    void add();

}

package com.geek.service.impl;

import com.geek.dao.IUserDao;
import com.geek.service.IUserService;

/**
 * @author geek
 */
public class UserServiceImpl implements IUserService {

    private IUserDao userDao;

    public void setUserDao(IUserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void add() {
        System.out.println("userService ~ add();");
        userDao.add();
    }

}

package com.geek.comtroller;

import com.geek.service.IUserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author geek
 */
public class UserController {

    public static void main(String[] args) {
        // 创建 Spring 的容器对象。
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        // 从容器对象中获取 UserService 对象。
        IUserService userService = applicationContext.getBean("userService", IUserService.class);
        // 调用 UserService 方法进行业务逻辑处理。
        userService.add();
        /*
        userService ~ add();
        userDao ~ add();
         */
    }

}


userService 对象是从 applicationContext 容器对象获取到的,也就是 userService 对象交由 Spring 进行管理。

调用 UserDao 对象中的 add(); 方法,也就是说 UserDao 子实现类对象也交由 Spring 管理。

UserService 中的 userDao 变量我们并没有进行赋值,但是可以正常使用,说明 Spring 已经将 UserDao 对象赋值给了 userDao 变量。

上面三点体现了 Spring 框架的 IoC(Inversion of Control)和 DI(Dependency Injection)。



Spring 核心功能结构。

Spring 大约有 20 个模块,由 1300 多个不同的文件构成。这些模块可以分为

核心容器、AOP 和设备支持、数据访问与集成、Web 组件、通信报文和集成测试等,下面是 Spring 框架的总体架构图。

在这里插入图片描述

核心容器由 beans、core、context 和 expression(Spring Expression Language,SpEL)4 个模块组成。

  • spring-beans 和 spring-core 模块是 Spring 框架的核心模块,包含了控制反转(Inversion of Control,IoC)和依赖注入(Dependency Injection,DI)。
    BeanFactory 使用控制反转对应用程序的配置和依赖性规范与实际的应用程序代码进行了分离。BeanFactory 属于延时加载,也就是说在实例化容器对象后并不会自动实例化 Bean,只有当 Bean 被使用时,BeanFactory 才会对该 Bean 进行实例化与依赖关系的装配。
package com.geek.comtroller;

import com.geek.service.IUserService;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

/**
 * @author geek
 */
public class UserController {

    public static void main(String[] args) {
        // 创建 Spring 的容器对象。
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        // (此时创建 Bean)。
        // UserServiceImpl 创建。。。
        //UserDao 创建。。。
        // 从容器对象中获取 UserService 对象。
        IUserService userService = applicationContext.getBean("userService", IUserService.class);
        // 调用 UserService 方法进行业务逻辑处理。
        userService.add();
        /*
        userService ~ add();
        userDao ~ add();
         */

        // ~ ~ ~ ~ ~ ~ ~

        // 延时加载。

        // 创建 Spring 的容器对象。
        BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
        // 此时没有创建 Bean 对象。

        beanFactory.getBean("userService", IUserService.class);
        // (此时创建 Bean)。
        // UserServiceImpl 创建。。。
        //UserDao 创建。。。
        // 调用 UserService 方法进行业务逻辑处理。
        userService.add();
        /*
        userService ~ add();
        userDao ~ add();
         */

    }

}

spring-context 模块构架于核心模块之上,扩展了 BeanFactory,为 ta 添加了 Bean 生命周期控制、框架事件体系及资源加载透明化等功能。此外,该模块还提供了许多企业级支持,如邮件访问、远程访问、任务调度等,ApplicationContext 是该模块的核心接口,它的超类是 BeanFactory。与 BeanFactory 不同,ApplicationContext 实例化后会自动对所有的单实例 Bean 进行实例化与依赖关系的装配,使之处于待用状态。

在这里插入图片描述

spring-context-support 模块是对 Spring IoC 容器及 IoC 子容器的扩展支持。

spring-context-indexer 模块是 Spring 的类管理组件和 Classpath 扫描组件。

spring-expression 模块是统一表达式语言(EL)的扩展模块,可以查询、管理运行中的对象,同时也可以方便地调用对象方法,以及操作数组、集合等。ta 的语法类似于传统 EL,但提供了额外的功能,最出色的要数函数调用和简单字符串的模板函数。EL 的特性是基于 Spring 产品的需求而设计的,可以非常方便地同 Spring IoC 进行交互。


Bean。

Spring 就是面向 Bean 的编程(BOP, Bean Oriented Programming),Bean 在 Spring 中处于核心地位。Bean 对于 Spring 的意义就像 Object 对于 OOP 的意义一样,Spring 中没有 Bean 也就没有 Spring 存在的意义。Spring IoC 容器通过配置文件或者注解的方式来管理 Bean 对象之间的依赖关系。

Spring 中 Bean 用于对一个类进行封装。如下面的配置。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="userDao" class="com.geek.dao.impl.UserDaoImpl"/>

    <bean id="userService" class="com.geek.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"/>
    </bean>

</beans>

为什么 Bean 如此重要。

Spring 将 Bean 对象交由一个叫 IoC 容器进行管理。

Bean 对象之间的依赖关系在配置文件中体现,并由 Spring 完成。


Spring IoC。

BeanFactory。

Spring 中 Bean 的创建是典型的工厂模式,这一系列的 Bean 工厂,即 IoC 容器,为开发者管理对象之间的依赖关系提供了很多便利和基础服务,在 Spring 中有许多 IoC 容器的实现供用户选择,其相互关系如图所示。

在这里插入图片描述

在这里插入图片描述

其中,BeanFactory 作为最顶层的一个接口,定义了 IoC 容器的基本功能规范,BeanFactory 有三个重要的子接口:ListableBeanFactory、HierarchicalBeanFactory 和 AutowireCapableBeanFactory。但是从类图中我们可以发现最终的默认实现类是 DefaultListableBeanFactory,ta 实现了所有的接口。
那么为何要定义这么多层次的接口呢?

每个接口都有它的使用场合,主要是为了区分在 Spring 内部操作过程中对象的传递和转化,对对象的数据访问所做的限制。例如,

ListableBeanFactory 接口表示这些 Bean 可列表化。
HierarchicalBeanFactory 表示这些 Bean 是有继承关系的,也就是每个 Bean 可能有父 Bean。
AutowireCapableBeanFactory 接口定义Bean的自动装配规则。

这三个接口共同定义了 Bean 的集合、Bean 之间的关系及 Bean 行为。最基本的 IoC 容器接口是 BeanFactory,来看一下它的源码。


package org.springframework.beans.factory;

import org.springframework.beans.BeansException;
import org.springframework.core.ResolvableType;
import org.springframework.lang.Nullable;

public interface BeanFactory {

	String FACTORY_BEAN_PREFIX = "&";

	// 根据 Bean 的名称获取 IoC 容器中的 Bean 对象。
	Object getBean(String name) throws BeansException;

	// 根据 bean 的名称获取 IoC 容器中的 bean 对象,并指定获取到的 bean 对象的类型,这样我们使用时就不需要进行类型强转了。
	<T> T getBean(String name, @Nullable Class<T> requiredType) throws BeansException;

	Object getBean(String name, Object... args) throws BeansException;

	<T> T getBean(Class<T> requiredType) throws BeansException;

	<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;

	// 判断容器中是否包含指定名称的 bean 对象。
	boolean containsBean(String name);

	// 根据 bean 的名称判断是否是单例。
	boolean isSingleton(String name) throws NoSuchBeanDefinitionException;

	boolean isPrototype(String name) throws NoSuchBeanDefinitionException;

	boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;

	boolean isTypeMatch(String name, @Nullable Class<?> typeToMatch) throws NoSuchBeanDefinitionException;

	@Nullable
	Class<?> getType(String name) throws NoSuchBeanDefinitionException;

	String[] getAliases(String name);

}

/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.beans.factory;

import org.springframework.beans.BeansException;
import org.springframework.core.ResolvableType;
import org.springframework.lang.Nullable;

/**
 * The root interface for accessing a Spring bean container.
 * This is the basic client view of a bean container;
 * further interfaces such as {@link ListableBeanFactory} and
 * {@link org.springframework.beans.factory.config.ConfigurableBeanFactory}
 * are available for specific purposes.
 *
 * <p>This interface is implemented by objects that hold a number of bean definitions,
 * each uniquely identified by a String name. Depending on the bean definition,
 * the factory will return either an independent instance of a contained object
 * (the Prototype design pattern), or a single shared instance (a superior
 * alternative to the Singleton design pattern, in which the instance is a
 * singleton in the scope of the factory). Which type of instance will be returned
 * depends on the bean factory configuration: the API is the same. Since Spring
 * 2.0, further scopes are available depending on the concrete application
 * context (e.g. "request" and "session" scopes in a web environment).
 *
 * <p>The point of this approach is that the BeanFactory is a central registry
 * of application components, and centralizes configuration of application
 * components (no more do individual objects need to read properties files,
 * for example). See chapters 4 and 11 of "Expert One-on-One J2EE Design and
 * Development" for a discussion of the benefits of this approach.
 *
 * <p>Note that it is generally better to rely on Dependency Injection
 * ("push" configuration) to configure application objects through setters
 * or constructors, rather than use any form of "pull" configuration like a
 * BeanFactory lookup. Spring's Dependency Injection functionality is
 * implemented using this BeanFactory interface and its subinterfaces.
 *
 * <p>Normally a BeanFactory will load bean definitions stored in a configuration
 * source (such as an XML document), and use the {@code org.springframework.beans}
 * package to configure the beans. However, an implementation could simply return
 * Java objects it creates as necessary directly in Java code. There are no
 * constraints on how the definitions could be stored: LDAP, RDBMS, XML,
 * properties file, etc. Implementations are encouraged to support references
 * amongst beans (Dependency Injection).
 *
 * <p>In contrast to the methods in {@link ListableBeanFactory}, all of the
 * operations in this interface will also check parent factories if this is a
 * {@link HierarchicalBeanFactory}. If a bean is not found in this factory instance,
 * the immediate parent factory will be asked. Beans in this factory instance
 * are supposed to override beans of the same name in any parent factory.
 *
 * <p>Bean factory implementations should support the standard bean lifecycle interfaces
 * as far as possible. The full set of initialization methods and their standard order is:
 * <ol>
 * <li>BeanNameAware's {@code setBeanName}
 * <li>BeanClassLoaderAware's {@code setBeanClassLoader}
 * <li>BeanFactoryAware's {@code setBeanFactory}
 * <li>EnvironmentAware's {@code setEnvironment}
 * <li>EmbeddedValueResolverAware's {@code setEmbeddedValueResolver}
 * <li>ResourceLoaderAware's {@code setResourceLoader}
 * (only applicable when running in an application context)
 * <li>ApplicationEventPublisherAware's {@code setApplicationEventPublisher}
 * (only applicable when running in an application context)
 * <li>MessageSourceAware's {@code setMessageSource}
 * (only applicable when running in an application context)
 * <li>ApplicationContextAware's {@code setApplicationContext}
 * (only applicable when running in an application context)
 * <li>ServletContextAware's {@code setServletContext}
 * (only applicable when running in a web application context)
 * <li>{@code postProcessBeforeInitialization} methods of BeanPostProcessors
 * <li>InitializingBean's {@code afterPropertiesSet}
 * <li>a custom init-method definition
 * <li>{@code postProcessAfterInitialization} methods of BeanPostProcessors
 * </ol>
 *
 * <p>On shutdown of a bean factory, the following lifecycle methods apply:
 * <ol>
 * <li>{@code postProcessBeforeDestruction} methods of DestructionAwareBeanPostProcessors
 * <li>DisposableBean's {@code destroy}
 * <li>a custom destroy-method definition
 * </ol>
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @author Chris Beams
 * @since 13 April 2001
 * @see BeanNameAware#setBeanName
 * @see BeanClassLoaderAware#setBeanClassLoader
 * @see BeanFactoryAware#setBeanFactory
 * @see org.springframework.context.ResourceLoaderAware#setResourceLoader
 * @see org.springframework.context.ApplicationEventPublisherAware#setApplicationEventPublisher
 * @see org.springframework.context.MessageSourceAware#setMessageSource
 * @see org.springframework.context.ApplicationContextAware#setApplicationContext
 * @see org.springframework.web.context.ServletContextAware#setServletContext
 * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization
 * @see InitializingBean#afterPropertiesSet
 * @see org.springframework.beans.factory.support.RootBeanDefinition#getInitMethodName
 * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization
 * @see DisposableBean#destroy
 * @see org.springframework.beans.factory.support.RootBeanDefinition#getDestroyMethodName
 */
public interface BeanFactory {

	/**
	 * Used to dereference a {@link FactoryBean} instance and distinguish it from
	 * beans <i>created</i> by the FactoryBean. For example, if the bean named
	 * {@code myJndiObject} is a FactoryBean, getting {@code &myJndiObject}
	 * will return the factory, not the instance returned by the factory.
	 */
	String FACTORY_BEAN_PREFIX = "&";


	/**
	 * Return an instance, which may be shared or independent, of the specified bean.
	 * <p>This method allows a Spring BeanFactory to be used as a replacement for the
	 * Singleton or Prototype design pattern. Callers may retain references to
	 * returned objects in the case of Singleton beans.
	 * <p>Translates aliases back to the corresponding canonical bean name.
	 * Will ask the parent factory if the bean cannot be found in this factory instance.
	 * @param name the name of the bean to retrieve
	 * @return an instance of the bean
	 * @throws NoSuchBeanDefinitionException if there is no bean definition
	 * with the specified name
	 * @throws BeansException if the bean could not be obtained
	 */
	Object getBean(String name) throws BeansException;

	/**
	 * Return an instance, which may be shared or independent, of the specified bean.
	 * <p>Behaves the same as {@link #getBean(String)}, but provides a measure of type
	 * safety by throwing a BeanNotOfRequiredTypeException if the bean is not of the
	 * required type. This means that ClassCastException can't be thrown on casting
	 * the result correctly, as can happen with {@link #getBean(String)}.
	 * <p>Translates aliases back to the corresponding canonical bean name.
	 * Will ask the parent factory if the bean cannot be found in this factory instance.
	 * @param name the name of the bean to retrieve
	 * @param requiredType type the bean must match. Can be an interface or superclass
	 * of the actual class, or {@code null} for any match. For example, if the value
	 * is {@code Object.class}, this method will succeed whatever the class of the
	 * returned instance.
	 * @return an instance of the bean
	 * @throws NoSuchBeanDefinitionException if there is no such bean definition
	 * @throws BeanNotOfRequiredTypeException if the bean is not of the required type
	 * @throws BeansException if the bean could not be created
	 */
	<T> T getBean(String name, @Nullable Class<T> requiredType) throws BeansException;

	/**
	 * Return an instance, which may be shared or independent, of the specified bean.
	 * <p>Allows for specifying explicit constructor arguments / factory method arguments,
	 * overriding the specified default arguments (if any) in the bean definition.
	 * @param name the name of the bean to retrieve
	 * @param args arguments to use when creating a bean instance using explicit arguments
	 * (only applied when creating a new instance as opposed to retrieving an existing one)
	 * @return an instance of the bean
	 * @throws NoSuchBeanDefinitionException if there is no such bean definition
	 * @throws BeanDefinitionStoreException if arguments have been given but
	 * the affected bean isn't a prototype
	 * @throws BeansException if the bean could not be created
	 * @since 2.5
	 */
	Object getBean(String name, Object... args) throws BeansException;

	/**
	 * Return the bean instance that uniquely matches the given object type, if any.
	 * <p>This method goes into {@link ListableBeanFactory} by-type lookup territory
	 * but may also be translated into a conventional by-name lookup based on the name
	 * of the given type. For more extensive retrieval operations across sets of beans,
	 * use {@link ListableBeanFactory} and/or {@link BeanFactoryUtils}.
	 * @param requiredType type the bean must match; can be an interface or superclass.
	 * {@code null} is disallowed.
	 * @return an instance of the single bean matching the required type
	 * @throws NoSuchBeanDefinitionException if no bean of the given type was found
	 * @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found
	 * @throws BeansException if the bean could not be created
	 * @since 3.0
	 * @see ListableBeanFactory
	 */
	<T> T getBean(Class<T> requiredType) throws BeansException;

	/**
	 * Return an instance, which may be shared or independent, of the specified bean.
	 * <p>Allows for specifying explicit constructor arguments / factory method arguments,
	 * overriding the specified default arguments (if any) in the bean definition.
	 * <p>This method goes into {@link ListableBeanFactory} by-type lookup territory
	 * but may also be translated into a conventional by-name lookup based on the name
	 * of the given type. For more extensive retrieval operations across sets of beans,
	 * use {@link ListableBeanFactory} and/or {@link BeanFactoryUtils}.
	 * @param requiredType type the bean must match; can be an interface or superclass.
	 * {@code null} is disallowed.
	 * @param args arguments to use when creating a bean instance using explicit arguments
	 * (only applied when creating a new instance as opposed to retrieving an existing one)
	 * @return an instance of the bean
	 * @throws NoSuchBeanDefinitionException if there is no such bean definition
	 * @throws BeanDefinitionStoreException if arguments have been given but
	 * the affected bean isn't a prototype
	 * @throws BeansException if the bean could not be created
	 * @since 4.1
	 */
	<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;


	/**
	 * Does this bean factory contain a bean definition or externally registered singleton
	 * instance with the given name?
	 * <p>If the given name is an alias, it will be translated back to the corresponding
	 * canonical bean name.
	 * <p>If this factory is hierarchical, will ask any parent factory if the bean cannot
	 * be found in this factory instance.
	 * <p>If a bean definition or singleton instance matching the given name is found,
	 * this method will return {@code true} whether the named bean definition is concrete
	 * or abstract, lazy or eager, in scope or not. Therefore, note that a {@code true}
	 * return value from this method does not necessarily indicate that {@link #getBean}
	 * will be able to obtain an instance for the same name.
	 * @param name the name of the bean to query
	 * @return whether a bean with the given name is present
	 */
	boolean containsBean(String name);

	/**
	 * Is this bean a shared singleton? That is, will {@link #getBean} always
	 * return the same instance?
	 * <p>Note: This method returning {@code false} does not clearly indicate
	 * independent instances. It indicates non-singleton instances, which may correspond
	 * to a scoped bean as well. Use the {@link #isPrototype} operation to explicitly
	 * check for independent instances.
	 * <p>Translates aliases back to the corresponding canonical bean name.
	 * Will ask the parent factory if the bean cannot be found in this factory instance.
	 * @param name the name of the bean to query
	 * @return whether this bean corresponds to a singleton instance
	 * @throws NoSuchBeanDefinitionException if there is no bean with the given name
	 * @see #getBean
	 * @see #isPrototype
	 */
	boolean isSingleton(String name) throws NoSuchBeanDefinitionException;

	/**
	 * Is this bean a prototype? That is, will {@link #getBean} always return
	 * independent instances?
	 * <p>Note: This method returning {@code false} does not clearly indicate
	 * a singleton object. It indicates non-independent instances, which may correspond
	 * to a scoped bean as well. Use the {@link #isSingleton} operation to explicitly
	 * check for a shared singleton instance.
	 * <p>Translates aliases back to the corresponding canonical bean name.
	 * Will ask the parent factory if the bean cannot be found in this factory instance.
	 * @param name the name of the bean to query
	 * @return whether this bean will always deliver independent instances
	 * @throws NoSuchBeanDefinitionException if there is no bean with the given name
	 * @since 2.0.3
	 * @see #getBean
	 * @see #isSingleton
	 */
	boolean isPrototype(String name) throws NoSuchBeanDefinitionException;

	/**
	 * Check whether the bean with the given name matches the specified type.
	 * More specifically, check whether a {@link #getBean} call for the given name
	 * would return an object that is assignable to the specified target type.
	 * <p>Translates aliases back to the corresponding canonical bean name.
	 * Will ask the parent factory if the bean cannot be found in this factory instance.
	 * @param name the name of the bean to query
	 * @param typeToMatch the type to match against (as a {@code ResolvableType})
	 * @return {@code true} if the bean type matches,
	 * {@code false} if it doesn't match or cannot be determined yet
	 * @throws NoSuchBeanDefinitionException if there is no bean with the given name
	 * @since 4.2
	 * @see #getBean
	 * @see #getType
	 */
	boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;

	/**
	 * Check whether the bean with the given name matches the specified type.
	 * More specifically, check whether a {@link #getBean} call for the given name
	 * would return an object that is assignable to the specified target type.
	 * <p>Translates aliases back to the corresponding canonical bean name.
	 * Will ask the parent factory if the bean cannot be found in this factory instance.
	 * @param name the name of the bean to query
	 * @param typeToMatch the type to match against (as a {@code Class})
	 * @return {@code true} if the bean type matches,
	 * {@code false} if it doesn't match or cannot be determined yet
	 * @throws NoSuchBeanDefinitionException if there is no bean with the given name
	 * @since 2.0.1
	 * @see #getBean
	 * @see #getType
	 */
	boolean isTypeMatch(String name, @Nullable Class<?> typeToMatch) throws NoSuchBeanDefinitionException;

	/**
	 * Determine the type of the bean with the given name. More specifically,
	 * determine the type of object that {@link #getBean} would return for the given name.
	 * <p>For a {@link FactoryBean}, return the type of object that the FactoryBean creates,
	 * as exposed by {@link FactoryBean#getObjectType()}.
	 * <p>Translates aliases back to the corresponding canonical bean name.
	 * Will ask the parent factory if the bean cannot be found in this factory instance.
	 * @param name the name of the bean to query
	 * @return the type of the bean, or {@code null} if not determinable
	 * @throws NoSuchBeanDefinitionException if there is no bean with the given name
	 * @since 1.1.2
	 * @see #getBean
	 * @see #isTypeMatch
	 */
	@Nullable
	Class<?> getType(String name) throws NoSuchBeanDefinitionException;

	/**
	 * Return the aliases for the given bean name, if any.
	 * All of those aliases point to the same bean when used in a {@link #getBean} call.
	 * <p>If the given name is an alias, the corresponding original bean name
	 * and other aliases (if any) will be returned, with the original bean name
	 * being the first element in the array.
	 * <p>Will ask the parent factory if the bean cannot be found in this factory instance.
	 * @param name the bean name to check for aliases
	 * @return the aliases, or an empty array if none
	 * @see #getBean
	 */
	String[] getAliases(String name);

}

在 BeanFactory 里只对 IoC 容器的基本行为做了定义,根本不关心你的 Bean 是如何定义及怎样加载的。正如我们只关心能从工厂里得到什么产品,不关心工厂是怎么生产这些产品的。

BeanFactory 有一个很重要的子接口,就是 ApplicationContext 接口,该接口主要来规范容器中的 bean 对象是非延时加载,即在创建容器对象的时候就对象 bean 进行初始化,并存储到一个容器中。

在这里插入图片描述

要知道工厂是如何产生对象的,我们需要看具体的 IoC 容器实现,Spring 提供了许多 IoC 容器实现。eg.

  • ClasspathXmlApplicationContext
    根据类路径加载 xml 配置文件,并创建 IoC 容器对象。
  • FileSystemXmlApplicationContext。
    根据系统路径加载 xml 配置文件,并创建 IoC 容器对象。
  • AnnotationConfigApplicationContext。
    加载注解类配置,并创建 IoC 容器。

BeanDefinition。

Spring IoC 容器管理我们定义的各种 Bean 对象及其相互关系,而 Bean 对象在 Spring 实现中是以 BeanDefinition 来描述的,如下面配置文件。

    <bean id="userDao" class="com.geek.dao.impl.UserDaoImpl"/>

在这里插入图片描述

在这里插入图片描述


BeanDefinitionReader。

Bean 的解析过程非常复杂,功能被分得很细,因为这里需要被扩展的地方很多,必须保证足够的灵活性,以应对可能的变化。Bean 的解析主要就是对 Spring 配置文件的解析。这个解析过程主要通过
BeanDefinitionReader 来完成,看看 Spring 中 BeanDefinitionReader 的类结构图。

在这里插入图片描述

/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.beans.factory.support;

import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.lang.Nullable;

/**
 * Simple interface for bean definition readers.
 * Specifies load methods with Resource and String location parameters.
 *
 * <p>Concrete bean definition readers can of course add additional
 * load and register methods for bean definitions, specific to
 * their bean definition format.
 *
 * <p>Note that a bean definition reader does not have to implement
 * this interface. It only serves as suggestion for bean definition
 * readers that want to follow standard naming conventions.
 *
 * @author Juergen Hoeller
 * @since 1.1
 * @see org.springframework.core.io.Resource
 */
public interface BeanDefinitionReader {

	// 获取 BeanDefinitionRegistry 注册器对象。

	/**
	 * Return the bean factory to register the bean definitions with.
	 * <p>The factory is exposed through the BeanDefinitionRegistry interface,
	 * encapsulating the methods that are relevant for bean definition handling.
	 */
	BeanDefinitionRegistry getRegistry();

	/**
	 * Return the resource loader to use for resource locations.
	 * Can be checked for the <b>ResourcePatternResolver</b> interface and cast
	 * accordingly, for loading multiple resources for a given resource pattern.
	 * <p>A {@code null} return value suggests that absolute resource loading
	 * is not available for this bean definition reader.
	 * <p>This is mainly meant to be used for importing further resources
	 * from within a bean definition resource, for example via the "import"
	 * tag in XML bean definitions. It is recommended, however, to apply
	 * such imports relative to the defining resource; only explicit full
	 * resource locations will trigger absolute resource loading.
	 * <p>There is also a {@code loadBeanDefinitions(String)} method available,
	 * for loading bean definitions from a resource location (or location pattern).
	 * This is a convenience to avoid explicit ResourceLoader handling.
	 * @see #loadBeanDefinitions(String)
	 * @see org.springframework.core.io.support.ResourcePatternResolver
	 */
	@Nullable
	ResourceLoader getResourceLoader();

	/**
	 * Return the class loader to use for bean classes.
	 * <p>{@code null} suggests to not load bean classes eagerly
	 * but rather to just register bean definitions with class names,
	 * with the corresponding Classes to be resolved later (or never).
	 */
	@Nullable
	ClassLoader getBeanClassLoader();

	/**
	 * Return the BeanNameGenerator to use for anonymous beans
	 * (without explicit bean name specified).
	 */
	BeanNameGenerator getBeanNameGenerator();


	/*
		下面的 loadBeanDefinitions 都是加载 bean 定义,从指定的资源中。
	*/

	/**
	 * Load bean definitions from the specified resource.
	 * @param resource the resource descriptor
	 * @return the number of bean definitions found
	 * @throws BeanDefinitionStoreException in case of loading or parsing errors
	 */
	int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException;

	/**
	 * Load bean definitions from the specified resources.
	 * @param resources the resource descriptors
	 * @return the number of bean definitions found
	 * @throws BeanDefinitionStoreException in case of loading or parsing errors
	 */
	int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException;

	/**
	 * Load bean definitions from the specified resource location.
	 * <p>The location can also be a location pattern, provided that the
	 * ResourceLoader of this bean definition reader is a ResourcePatternResolver.
	 * @param location the resource location, to be loaded with the ResourceLoader
	 * (or ResourcePatternResolver) of this bean definition reader
	 * @return the number of bean definitions found
	 * @throws BeanDefinitionStoreException in case of loading or parsing errors
	 * @see #getResourceLoader()
	 * @see #loadBeanDefinitions(org.springframework.core.io.Resource)
	 * @see #loadBeanDefinitions(org.springframework.core.io.Resource[])
	 */
	int loadBeanDefinitions(String location) throws BeanDefinitionStoreException;

	/**
	 * Load bean definitions from the specified resource locations.
	 * @param locations the resource locations, to be loaded with the ResourceLoader
	 * (or ResourcePatternResolver) of this bean definition reader
	 * @return the number of bean definitions found
	 * @throws BeanDefinitionStoreException in case of loading or parsing errors
	 */
	int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException;

}


BeanDefinitionRegistry。

BeanDefinitionReader 用来解析 bean 定义,并封装 BeanDefinition 对象,而我们定义的配置文件中定义了很多 bean 标签,所以就有一个问题,解析的 BeanDefinition 对象存储到哪儿?答案就是 BeanDefinition 的注册中心,而该注册中心顶层接口就是 BeanDefinitionRegistry。

在这里插入图片描述

在这里插入图片描述

从上面类图可以看到 BeanDefinitionRegistry 接口的子实现类主要有以下几个。

  • DefaultListableBeanFactory
    在该类中定义了如下代码,就是用来注册 bean。
@SuppressWarnings("serial")
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {


	/** Map of bean definition objects, keyed by bean name */
	private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
  • SimpleBeanDefinitionRegistry
    在该类中定义了如下代码,就是用来注册 bean。
public class SimpleBeanDefinitionRegistry extends SimpleAliasRegistry implements BeanDefinitionRegistry {


	/** Map of bean definition objects, keyed by bean name */
	private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(64);

/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.beans.factory.support;

import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.core.AliasRegistry;

/**
 * Interface for registries that hold bean definitions, for example RootBeanDefinition
 * and ChildBeanDefinition instances. Typically implemented by BeanFactories that
 * internally work with the AbstractBeanDefinition hierarchy.
 *
 * <p>This is the only interface in Spring's bean factory packages that encapsulates
 * <i>registration</i> of bean definitions. The standard BeanFactory interfaces
 * only cover access to a <i>fully configured factory instance</i>.
 *
 * <p>Spring's bean definition readers expect to work on an implementation of this
 * interface. Known implementors within the Spring core are DefaultListableBeanFactory
 * and GenericApplicationContext.
 *
 * @author Juergen Hoeller
 * @since 26.11.2003
 * @see org.springframework.beans.factory.config.BeanDefinition
 * @see AbstractBeanDefinition
 * @see RootBeanDefinition
 * @see ChildBeanDefinition
 * @see DefaultListableBeanFactory
 * @see org.springframework.context.support.GenericApplicationContext
 * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
 * @see PropertiesBeanDefinitionReader
 */
public interface BeanDefinitionRegistry extends AliasRegistry {

	/**
	 * Register a new bean definition with this registry.
	 * Must support RootBeanDefinition and ChildBeanDefinition.
	 * @param beanName the name of the bean instance to register
	 * @param beanDefinition definition of the bean instance to register
	 * @throws BeanDefinitionStoreException if the BeanDefinition is invalid
	 * or if there is already a BeanDefinition for the specified bean name
	 * (and we are not allowed to override it)
	 * @see RootBeanDefinition
	 * @see ChildBeanDefinition
	 */
	// 往注册表中注册 bean。
	void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
			throws BeanDefinitionStoreException;

	/**
	 * Remove the BeanDefinition for the given name.
	 * @param beanName the name of the bean instance to register
	 * @throws NoSuchBeanDefinitionException if there is no such bean definition
	 */
	// 从注册表中删除指定名称的 bean。
	void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;

	/**
	 * Return the BeanDefinition for the given bean name.
	 * @param beanName name of the bean to find a definition for
	 * @return the BeanDefinition for the given name (never {@code null})
	 * @throws NoSuchBeanDefinitionException if there is no such bean definition
	 */
	// 获取注册表中指定名称的 bean。
	BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;

	/**
	 * Check if this registry contains a bean definition with the given name.
	 * @param beanName the name of the bean to look for
	 * @return if this registry contains a bean definition with the given name
	 */
	// 判断注册表中是否已经注册了指定名称的 bean。
	boolean containsBeanDefinition(String beanName);

	/**
	 * Return the names of all beans defined in this registry.
	 * @return the names of all beans defined in this registry,
	 * or an empty array if none defined
	 */
	// 获取注册表中所有 bean 的名称。
	String[] getBeanDefinitionNames();

	/**
	 * Return the number of beans defined in the registry.
	 * @return the number of beans defined in the registry
	 */
	int getBeanDefinitionCount();

	/**
	 * Determine whether the given bean name is already in use within this registry,
	 * i.e. whether there is a local bean or alias registered under this name.
	 * @param beanName the name to check
	 * @return whether the given bean name is already in use
	 */
	boolean isBeanNameInUse(String beanName);

}


创建容器。

ClassPathXmlApplicationContext 对 Bean 配置资源的载入是从 refresh(); 方法开始的。

refresh(); 方法是一个模板方法,规定了 IoC 容器的启动流程,有些逻辑要交给其子类实现。ta 对 Bean 配置资源进行载入,ClassPathXmlApplicationContext 通过调用其父类 AbstractApplicationContext 的 refresh(); 方法启动整个 IoC 容器对 Bean 定义的载入过程。


/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.context.support;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

/**
 * Standalone XML application context, taking the context definition files
 * from the class path, interpreting plain paths as class path resource names
 * that include the package path (e.g. "mypackage/myresource.txt"). Useful for
 * test harnesses as well as for application contexts embedded within JARs.
 *
 * <p>The config location defaults can be overridden via {@link #getConfigLocations},
 * Config locations can either denote concrete files like "/myfiles/context.xml"
 * or Ant-style patterns like "/myfiles/*-context.xml" (see the
 * {@link org.springframework.util.AntPathMatcher} javadoc for pattern details).
 *
 * <p>Note: In case of multiple config locations, later bean definitions will
 * override ones defined in earlier loaded files. This can be leveraged to
 * deliberately override certain bean definitions via an extra XML file.
 *
 * <p><b>This is a simple, one-stop shop convenience ApplicationContext.
 * Consider using the {@link GenericApplicationContext} class in combination
 * with an {@link org.springframework.beans.factory.xml.XmlBeanDefinitionReader}
 * for more flexible context setup.</b>
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @see #getResource
 * @see #getResourceByPath
 * @see GenericApplicationContext
 */
public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {

	@Nullable
	private Resource[] configResources;


	/**
	 * Create a new ClassPathXmlApplicationContext with the given parent,
	 * loading the definitions from the given XML files.
	 * @param configLocations array of resource locations
	 * @param refresh whether to automatically refresh the context,
	 * loading all bean definitions and creating all singletons.
	 * Alternatively, call refresh manually after further configuring the context.
	 * @param parent the parent context
	 * @throws BeansException if context creation failed
	 * @see #refresh()
	 */
	public ClassPathXmlApplicationContext(
			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
			throws BeansException {

		super(parent);
		setConfigLocations(configLocations);
		if (refresh) {
			refresh();
		}
	}

自定义 Spring IoC。

现要对下面的配置文件进行解析,并自定义 Spring 框架的 IoC 对涉及到的对象进行管理。

<?xml version="1.0" encoding="UTF-8"?>

<beans>

    <bean id="userDao" class="com.geek.dao.impl.UserDaoImpl"/>

    <bean id="userService" class="com.geek.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"/>
    </bean>

</beans>

定义 Bean 相关的 pojo 类。
PropertyValue 类。

用于封装 bean 的属性,体现到上面的配置文件就是封装 bean 标签的子标签 property 标签数据。

package com.geek.spring.framework.beans;

/**
 * 封装 bean 标签下的 property 标签的属性。
 * name 属性。
 * ref 属性。
 * value 属性。
 *
 * @author geek
 */
public class PropertyValue {

    private String name;
    private String ref;
    private String value;

    public PropertyValue() {
    }

    public PropertyValue(String name, String ref, String value) {
        this.name = name;
        this.ref = ref;
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRef() {
        return ref;
    }

    public void setRef(String ref) {
        this.ref = ref;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        PropertyValue that = (PropertyValue) o;

        if (name != null ? !name.equals(that.name) : that.name != null) return false;
        if (ref != null ? !ref.equals(that.ref) : that.ref != null) return false;
        return value != null ? value.equals(that.value) : that.value == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + (ref != null ? ref.hashCode() : 0);
        result = 31 * result + (value != null ? value.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "PropertyValue{" +
                "name='" + name + '\'' +
                ", ref='" + ref + '\'' +
                ", value='" + value + '\'' +
                '}';
    }

}


MutablePropertyValues 类。

一个 bean 标签可以有多个 property 子标签,所以再定义一个 MutablePropertyValues 类,用来存储并管理多个 PropertyValue 对象。

package com.geek.spring.framework.beans;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 存储和管理 Property 对象。
 *
 * @author geek
 */
public class MutablePropertyValues implements Iterable<PropertyValue> {

    /**
     * 定义 List 集合对象,用来存储 PropertyValue 对象。
     */
    private final List<PropertyValue> propertyValueList;

    public MutablePropertyValues() {
        this.propertyValueList = new ArrayList<PropertyValue>();
    }

    public MutablePropertyValues(List<PropertyValue> propertyValueList) {
        this.propertyValueList = (propertyValueList != null ?
                propertyValueList : new ArrayList<PropertyValue>());
    }

    public List<PropertyValue> getPropertyValueList() {
        return propertyValueList;
    }

    /**
     * 获取迭代器对象。
     *
     * @return
     */
    @Override
    public Iterator<PropertyValue> iterator() {
        return propertyValueList.iterator();
    }

    /**
     * 获取所有的 PropertyValue 对象,返回以数组的形式。
     *
     * @return
     */
    public PropertyValue[] getPropertyValues() {
        // toArray(); 转为数组,[] 长度随意。
        return this.propertyValueList.toArray(new PropertyValue[0]);
    }

    /**
     * 根据 name 属性值获取 PropertyValue 对象。
     *
     * @param propertyName
     * @return
     */
    public PropertyValue getPropertyValue(String propertyName) {
        if (isEmpty()) {
            for (PropertyValue propertyValue : this.propertyValueList) {
                if (propertyValue.getName().equals(propertyName)) {
                    return propertyValue;
                }
            }
        }
        return null;
    }

    /**
     * 判断集合是否为空。
     *
     * @return
     */
    public boolean isEmpty() {
        return this.propertyValueList.isEmpty();
    }

    /**
     * 添加 PropertyValue 对象。
     *
     * @param propertyValue
     * @return
     */
    public MutablePropertyValues addPropertyValue(PropertyValue propertyValue) {
        for (int i = 0; i < this.propertyValueList.size(); i++) {
            // 获取集合中每一个 PropertyValue 对象。
            PropertyValue currentPropertyValue = this.propertyValueList.get(i);
            if (currentPropertyValue.getName().equals(propertyValue.getName())) {
                // 如果集合中存储的的 PropertyValue 和传递进来的重复了,进行覆盖。
                this.propertyValueList.set(i, new PropertyValue(propertyValue.getName(), propertyValue.getRef(), propertyValue.getValue()));
                // 目的:实现链式编程。
                return this;
            }
        }
        this.propertyValueList.add(propertyValue);
        // 目的:实现链式编程。
        return this;
    }

    /**
     * 判断是否有指定 name 属性值的对象。
     *
     * @param propertyName
     * @return
     */
    public boolean contains(String propertyName) {
        return getPropertyValue(propertyName) != null;
    }

}


BeanDefinition 类。

BeanDefinition 类用来封装 bean 信息,主要包含 id(即 bean 对象的名称)、class(需要交由 Spring 管理的类的全类名)及子标签 property 数据。

package com.geek.spring.framework.beans;

/**
 * 封装 Bean 标签数据。
 * id 属性。
 * class 属性。
 * property 子标签数据。
 *
 * @author geek
 */
public class BeanDefinition {

    private String id;
    private String className;

    private MutablePropertyValues mutablePropertyValues;

    public BeanDefinition() {
        mutablePropertyValues = new MutablePropertyValues();
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public MutablePropertyValues getMutablePropertyValues() {
        return mutablePropertyValues;
    }

    public void setMutablePropertyValues(MutablePropertyValues mutablePropertyValues) {
        this.mutablePropertyValues = mutablePropertyValues;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        BeanDefinition that = (BeanDefinition) o;

        if (id != null ? !id.equals(that.id) : that.id != null) return false;
        if (className != null ? !className.equals(that.className) : that.className != null) return false;
        return mutablePropertyValues != null ? mutablePropertyValues.equals(that.mutablePropertyValues) : that.mutablePropertyValues == null;
    }

    @Override
    public int hashCode() {
        int result = id != null ? id.hashCode() : 0;
        result = 31 * result + (className != null ? className.hashCode() : 0);
        result = 31 * result + (mutablePropertyValues != null ? mutablePropertyValues.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "BeanDefinition{" +
                "id='" + id + '\'' +
                ", className='" + className + '\'' +
                ", mutablePropertyValues=" + mutablePropertyValues +
                '}';
    }

}


定义注册表相关类。
IBeanDefinitionRegistry 接口。

IBeanDefinitionRegistry 接口定义了注册表的相关操作,定义如下功能。

  • 注册 BeanDefinition 对象到注册表中。
  • 从注册表中删除指定名称 BeanDefinition 对象。
  • 根据名称从注册表中获取 BeanDefinition 对象。
  • 判断注册表中是否包含指定名称的 BeanDefinition 对象。
  • 获取注册表中所有 BeanDefinition 名称。
  • 获取注册表中 BeanDefinition 对象个数。
package com.geek.spring.framework.beans.factory.support;

import com.geek.spring.framework.beans.BeanDefinition;

/**
 * 注册表对象。
 *
 * @author geek
 */
public interface IBeanDefinitionRegistry {

    /**
     * 注册 BeanDefinition 对象到注册表中。
     *
     * @param beanName
     * @param beanDefinition
     */
    void registerBeanDefinition(String beanName, BeanDefinition beanDefinition);

    /**
     * 从注册表中删除指定名称 BeanDefinition 对象。
     *
     * @param beanName
     */
    void removeBeanDefinition(String beanName);

    /**
     * 根据名称从注册表中获取 BeanDefinition 对象。
     *
     * @param beanName
     * @return
     */
    BeanDefinition getBeanDefinition(String beanName);

    /**
     * 判断注册表中是否包含指定名称 BeanDefinition 对象。
     *
     * @param beanName
     * @return
     */
    boolean containsBeanDefinition(String beanName);

    /**
     * 获取注册表中所有 BeanDefinition 名称。
     *
     * @return
     */
    String[] getBeanDefinitionNames();

    /**
     * 获取注册表中 BeanDefinition 对象个数。
     *
     * @return
     */
    int getBeanDefinitionCount();

//    boolean isBeanNameInUse(String beanName);

}


SimpleBeanDefinitionRegistry 类。

该类实现了 BeanDefinitionRegistry 接口,定义了 Map 集合作为注册表容器。

package com.geek.spring.framework.beans.factory.support;

import com.geek.spring.framework.beans.BeanDefinition;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 注册表接口的子实现类。
 *
 * @author geek
 */
public class SimpleBeanDefinitionRegistry implements IBeanDefinitionRegistry {

    /**
     * 存储 BeanDefinition 的容器对象。
     * Map of bean definition objects, keyed by bean name
     */
    private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(64);

    /**
     * 注册 BeanDefinition 对象到注册表中。
     *
     * @param beanName
     * @param beanDefinition
     */
    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
        this.beanDefinitionMap.put(beanName, beanDefinition);
    }

    /**
     * 从注册表中删除指定名称 BeanDefinition 对象。
     *
     * @param beanName
     */
    @Override
    public void removeBeanDefinition(String beanName) {
//        if (this.beanDefinitionMap.remove(beanName) == null) {
//            throw new NoSuchBeanDefinitionException(beanName);
//        }
        this.beanDefinitionMap.remove(beanName);
    }

    /**
     * 根据名称从注册表中获取 BeanDefinition 对象。
     *
     * @param beanName
     * @return
     */
    @Override
    public BeanDefinition getBeanDefinition(String beanName) {
//        BeanDefinition bd = this.beanDefinitionMap.get(beanName);
//        if (bd == null) {
//            throw new NoSuchBeanDefinitionException(beanName);
//        }
//        return bd;
        BeanDefinition bd = this.beanDefinitionMap.get(beanName);
        return bd;
    }

    /**
     * 判断注册表中是否包含指定名称 BeanDefinition 对象。
     *
     * @param beanName
     * @return
     */
    @Override
    public boolean containsBeanDefinition(String beanName) {
        return this.beanDefinitionMap.containsKey(beanName);
    }

    /**
     * 获取注册表中所有 BeanDefinition 名称。
     *
     * @return
     */
    @Override
    public String[] getBeanDefinitionNames() {
        return this.beanDefinitionMap.keySet().toArray(new String[0]);
    }

    /**
     * 获取注册表中 BeanDefinition 对象个数。
     *
     * @return
     */
    @Override
    public int getBeanDefinitionCount() {
        return this.beanDefinitionMap.size();
    }

//    @Override
//    public boolean isBeanNameInUse(String beanName) {
//        return isAlias(beanName) || containsBeanDefinition(beanName);
//    }

}


定义解析器相关类。
IBeanDefinitionReader 接口。

IBeanDefinitionReader 是用来解析配置文件并在注册表中注册 bean 的信息。定义了两个规范。

  • 获取注册表的功能,让外界可以通过该对象获取注册表对象。
  • 加载配置文件,并注册 bean 数据。
package com.geek.spring.framework.beans.factory.support;

/**
 * 解析配置文件。该接口只定义了规范。
 *
 * @author geek
 */
public interface IBeanDefinitionReader {

    /**
     * 获取注册表对象。
     *
     * @return
     */
    IBeanDefinitionRegistry getRegistry();

    /**
     * 加载配置文件并在注册表中进行注册。
     *
     * @param location
     * @return
     */
    void loadBeanDefinitions(String location);

}


XmlBeanDefinitionReader 类。

XmlBeanDefinitionReader 类是专门用来解析 xml 配置文件的。该类实现 IBeanDefinitionReader 接口并实现接口中的两个功能。

    <dependencies>
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
    </dependencies>
package com.geek.spring.framework.beans.factory.xml;

import com.geek.spring.framework.beans.BeanDefinition;
import com.geek.spring.framework.beans.MutablePropertyValues;
import com.geek.spring.framework.beans.PropertyValue;
import com.geek.spring.framework.beans.factory.support.IBeanDefinitionReader;
import com.geek.spring.framework.beans.factory.support.IBeanDefinitionRegistry;
import com.geek.spring.framework.beans.factory.support.SimpleBeanDefinitionRegistry;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * 针对 xml 配置文件进行解析。
 *
 * @author geek
 */
public class XmlBeanDefinitionReader implements IBeanDefinitionReader {

    /**
     * 声明注册表对象。
     */
    private IBeanDefinitionRegistry beanDefinitionRegistry;

    public XmlBeanDefinitionReader() {
        this.beanDefinitionRegistry = new SimpleBeanDefinitionRegistry();
    }

    /**
     * 获取注册表对象。
     *
     * @return
     */
    @Override
    public IBeanDefinitionRegistry getRegistry() {
        return beanDefinitionRegistry;
    }

    /**
     * 加载配置文件并在注册表中进行注册。
     *
     * @param location
     * @return
     */
    @Override
    public void loadBeanDefinitions(String location) throws DocumentException {
        // 获取类路径下的配置文件。
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(location);
        // 使用 dom4j 进行 xml 配置文件解析。
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        // 根据 Document 对象获取根元素对象。
        Element rootElement = document.getRootElement();

        // 解析 bean 标签。
        parseBean(rootElement);
    }

    /**
     * 解析 xml 文件。
     *
     * @param rootElement
     */
    private void parseBean(Element rootElement) {
        // 获取根标签下索引 Bean 标签对象。
        List<Element> beanElements = rootElement.elements("bean");
        // 遍历集合。
        for (Element beanElement : beanElements) {
            // 获取 id 属性。
            String id = beanElement.attributeValue("id");
            // 获取 class 属性。
            String className = beanElement.attributeValue("class");
            // 将 id 属性和 class 属性封装到 BeanDefinition 对象中。
            // 创建 BeanDefinition 对象。
            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setId(id);
            beanDefinition.setClassName(className);

            // 获取 Bean 标签下所有的 property 标签对象。
            List<Element> propertyElements = beanElement.elements("property");
            // 创建 MutablePropertyValues 对象。
            MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();

            for (Element propertyElement : propertyElements) {
                String name = propertyElement.attributeValue("name");
                String ref = propertyElement.attributeValue("ref");
                String value = propertyElement.attributeValue("value");
                PropertyValue propertyValue = new PropertyValue(name, ref, value);
                mutablePropertyValues.addPropertyValue(propertyValue);
            }

            // 将 MutablePropertyValues 对象封装到 BeanDefinition 对象中。
            beanDefinition.setMutablePropertyValues(mutablePropertyValues);
            // 将 BeanDefinition 对象注册到注册表中。
            beanDefinitionRegistry.registerBeanDefinition(id, beanDefinition);
        }
    }

}


IoC 容器相关类。
IBeanFactory 接口。

在该接口中定义 IoC 容器的统一规范即获取 bean 对象。

package com.geek.spring.framework.beans.factory;

import java.lang.reflect.InvocationTargetException;

/**
 * IoC 容器父接口。
 *
 * @author geek
 */
public interface IBeanFactory {

    /**
     * 根据名称获取 Bean 对象。
     *
     * @param name
     * @return
     */
    Object getBean(String name) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException;

    /**
     * 根据名称和类型获取 Bean 对象。
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    <T> T getBean(String name, Class<? extends T> clazz) throws ClassNotFoundException, InvocationTargetException, InstantiationException, NoSuchMethodException, IllegalAccessException;

}


IApplicationContext 接口。

该接口的所以的子实现类对 bean 对象的创建都是非延时的,所以在该接口中定义 refresh(); 方法,该方法主要完成以下两个功能。

  • 加载配置文件。

  • 根据注册表中的 BeanDefinition 对象封装的数据进行 bean 对象的创建。

package com.geek.spring.framework.context;

import com.geek.spring.framework.beans.factory.IBeanFactory;
import org.dom4j.DocumentException;

/**
 * 非延时加载功能。
 *
 * @author geek
 */
public interface IApplicationContext extends IBeanFactory {

    void refresh() throws DocumentException;

}


AbstractApplicationContext 类。
  • 作为 ApplicationContext 接口的子类,所以该类也是非延时加载,所以需要在该类中定义一个 Map 集合,作为 bean 对象存储的容器。

  • 声明 BeanDefinitionReader 类型的变量,用来进行 xml 配置文件的解析,符合单一职责原则。

BeanDefinitionReader 类型的对象创建交由子类实现,因为只有子类明确到底创建 BeanDefinitionReader 哪儿个子实现类对象。

package com.geek.spring.framework.context.support;

import com.geek.spring.framework.beans.BeanDefinition;
import com.geek.spring.framework.beans.factory.support.IBeanDefinitionReader;
import com.geek.spring.framework.beans.factory.support.IBeanDefinitionRegistry;
import com.geek.spring.framework.context.IApplicationContext;
import org.dom4j.DocumentException;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * ApplicationContext 接口的子实现类。
 * 用于立即加载。
 *
 * @author geek
 */
public abstract class AbstractApplicationContext implements IApplicationContext {

    /**
     * 声明解析器。
     */
    protected IBeanDefinitionReader beanDefinitionReader;

    /**
     * 定义用于存储 Bean 对象的 Map 容器。
     */
    protected Map<String, Object> singletonObjects = new HashMap<>();

    /**
     * 声明配置文件路径的变量。
     */
    protected String configLocation;

    @Override
    public void refresh() throws DocumentException, ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        // 加载 BeanDefinition 对象。
        beanDefinitionReader.loadBeanDefinitions(configLocation);
        // 初始化 Bean。
        finishBeanInitialization();
    }

    /**
     * 初始化 Bean。
     * 模板方法模式。
     */
    private void finishBeanInitialization() throws ClassNotFoundException, InvocationTargetException, InstantiationException, NoSuchMethodException, IllegalAccessException {
        // 获取注册表对象。
        IBeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();
        // 获取 BeanDefinition 对象。
        String[] beanNames = registry.getBeanDefinitionNames();
        // 进行 Bean 的初始化。
        for (String beanName : beanNames) {
            BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
            getBean(beanName);
        }
    }

}

注意:该类 finishBeanInitialization(); 方法中调用 getBean(); 方法使用到了模板方法模式。


ClassPathXmlApplicationContext 类。

该类主要是加载类路径下的配置文件,并进行 bean 对象的创建,主要完成以下功能。

  • 在构造方法中,创建 BeanDefinitionReader 对象。

  • 在构造方法中,调用 refresh(); 方法,用于进行配置文件加载、创建 bean 对象并存储到容器中。

  • 重写父接口中的 getBean(); 方法,并实现依赖注入操作。

package com.geek.spring.framework.context.support;

import com.geek.spring.framework.beans.BeanDefinition;
import com.geek.spring.framework.beans.MutablePropertyValues;
import com.geek.spring.framework.beans.PropertyValue;
import com.geek.spring.framework.beans.factory.support.IBeanDefinitionRegistry;
import com.geek.spring.framework.beans.factory.xml.XmlBeanDefinitionReader;
import com.geek.spring.framework.utils.StringUtils;
import org.dom4j.DocumentException;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * IoC 容器具体子实现类。
 * 用于加载类路径下的 xml 格式的配置文件。
 *
 * @author geek
 */
public class ClassPathXmlApplicationContext extends AbstractApplicationContext {

    public ClassPathXmlApplicationContext(String configLocation) {
        this.configLocation = configLocation;
        // 构建解析器对象。
        beanDefinitionReader = new XmlBeanDefinitionReader();
        try {
            this.refresh();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据名称获取 Bean 对象。
     *
     * @param name
     * @return
     */
    @Override
    public Object getBean(String name) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
        Object object = singletonObjects.get(name);
        // 判断对象容器中是否包含指定名称的 Bean 对象。
        // 如果包含,直接返回即可。
        if (object != null) {
            return object;
        }
        // 如果不包含,需要自行创建。
        // 获取注册表对象。
        IBeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();
        // 获取 BeanDefinition 对象。
        BeanDefinition beanDefinition = registry.getBeanDefinition(name);
        if (beanDefinition == null) {
            return null;
        }
        // 获取Bean 信息中的 className。
        String className = beanDefinition.getClassName();
        // 通过反射创建对象。
        Class<?> clazz = Class.forName(className);
        Object beanObj = clazz.newInstance();

        // 依赖注入。
        MutablePropertyValues propertyValues = beanDefinition.getMutablePropertyValues();
        // 迭代器模式。
        for (PropertyValue propertyValue : propertyValues) {
            // 获取配置文件 Bean 的属性。
            // name 属性。
            String propertyName = propertyValue.getName();
            // value 属性。
            String value = propertyValue.getValue();
            // ref 属性。
            String ref = propertyValue.getRef();
            // value 和 ref 属性只能有一个。
            if (ref != null && !"".equals(ref)) {
                // 获取依赖的 Bean 对象。(递归)。
                Object bean = getBean(ref);
                // 拼接方法名。
                String methodName =
                        StringUtils.getSetterMethodNameByFieldName(propertyName);
                // 反射获取所有的方法对象。
                Method[] methods = clazz.getMethods();
                for (Method method : methods) {
                    if (method.getName().equals(methodName)) {
                        // 执行该 setter 方法。(UserService set UserDao)。。。
                        method.invoke(beanObj, bean);
                    }
                }
            }
            if (value != null && !"".equals(value)) {
                // 拼接方法名。
                String methodName =
                        StringUtils.getSetterMethodNameByFieldName(propertyName);
                // 获取 method 对象。
                Method method = clazz.getMethod(methodName, String.class);
                method.invoke(beanObj, value);
            }
        }

        // 在返回对象之前,将该对象存入 Map 容器中。(复用)。
        singletonObjects.put(name, beanObj);

        return beanObj;
    }

    /**
     * 根据名称和类型获取 Bean 对象。
     *
     * @param name
     * @param clazz
     * @return
     */
    @Override
    public <T> T getBean(String name, Class<? extends T> clazz) throws ClassNotFoundException, InvocationTargetException, InstantiationException, NoSuchMethodException, IllegalAccessException {
        Object bean = getBean(name);
        if (bean != null) {
            return clazz.cast(bean);
        }
        return null;
    }

}

package com.geek.spring.framework.utils;

/**
 * @author geek
 */
public class StringUtils {

    private StringUtils() {

    }

    // userDao --> setUserDao。
    public static String getSetterMethodNameByFieldName(String fieldName) {
        return "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
    }

}


Spring IoC 总结。

使用到的设计模式。
  • 工厂模式。
    工厂模式 + 配置文件。

  • 单例模式。
    Spring IoC 管理的 bean 对象都是单例的,此处的单例不是通过构造器进行单例的控制的,而是 Spring框 架对每一个 bean 只创建了一个对象。

  • 模板方法模式。
    AbstractApplicationContext 类中的 finishBeanInitialization(); 方法调用了子类的 getBean(); 方法,因为 getBean(); 的实现和环境息息相关。

  • 迭代器模式。对于 MutablePropertyValues 类定义使用到了迭代器模式,因为此类存储并管理 PropertyValue 对象,也属于一个容器,所以给该容器提供一个遍历方式。

Spring 框架其实使用到了很多设计模式,如 AOP 使用到了代理模式,选择 JDK 代理或者 CGLIB 代理使用到了策略模式,还有适配器模式,装饰者模式,观察者模式等。


测试。

<?xml version="1.0" encoding="UTF-8"?>

<beans>

    <bean id="userDao" class="com.geek.my.dao.impl.UserDaoImpl">
        <property name="username" value="geek"/>
        <property name="password" value="123"/>
    </bean>

    <bean id="userService" class="com.geek.my.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"/>
    </bean>

</beans>

package com.geek.my.dao.impl;

import com.geek.my.dao.IUserDao;

/**
 * @author geek
 */
public class UserDaoImpl implements IUserDao {

    private String username;
    private String password;

    public UserDaoImpl() {
        System.out.println("UserDaoImpl 创建。。。");
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public void add() {
        System.out.println("userDao ~ add();");

        System.out.println("username = " + username);
        System.out.println("password = " + password);
    }

}

package com.geek.my.comtroller;

import com.geek.my.service.IUserService;
import com.geek.spring.framework.context.IApplicationContext;
import com.geek.spring.framework.context.support.ClassPathXmlApplicationContext;

import java.lang.reflect.InvocationTargetException;

/**
 * @author geek
 */
public class UserController {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        // 创建 Spring 的容器对象。
        IApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContextMY.xml");
        // (此时创建 Bean)。
        // UserServiceImpl 创建。。。
        //UserDao 创建。。。
        // 从容器对象中获取 UserService 对象。
        IUserService userService = applicationContext.getBean("userService", IUserService.class);
        // 调用 UserService 方法进行业务逻辑处理。
        userService.add();
        /*
        userService ~ add();
        userDao ~ add();
         */

        // ~ ~ ~ ~ ~ ~ ~

        // 延时加载。
//
//        // 创建 Spring 的容器对象。
//        IBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
//        // 此时没有创建 Bean 对象。
//
//        beanFactory.getBean("userService", IUserService.class);
//        // (此时创建 Bean)。
//        // UserServiceImpl 创建。。。
//        //UserDao 创建。。。
//        // 调用 UserService 方法进行业务逻辑处理。
//        userService.add();
//        /*
//        userService ~ add();
//        userDao ~ add();
//         */

    }

}


整个设计和 Spring 的设计还是有一定的出入。

Spring 框架底层是很复杂的,进行了很深入的封装,并对外提供了很好的扩展性。而我们自定义 Spring IoC 有以下几个目的。

了解 Spring 底层对对象的大体管理机制。

了解设计模式在具体的开发中的使用。

以后学习 Spring 源码,通过该案例的实现,可以降低 Spring 学习的入门成本。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lyfGeek

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值