Spring源码解析——start from BeanFactory(一)

简介:          先来看一下我们学习Spring时候的ABC代码: BeanFactory beanFactory=new ClassPathXmlApplicationContext("applicationContext.



         先来看一下我们学习Spring时候的ABC代码:


	BeanFactory beanFactory=new ClassPathXmlApplicationContext("applicationContext.xml");
		UserManager userManager=(UserManager)beanFactory.getBean("UserManagerImpl");
		userManager.add("dd","d");

             通过加在含有bean配置关系的映射文件,get到我们的beanFactory容器,之后就可以从容器中get bean了。接着,我们将跟着这几行最简单代码,来深入search下spring是如何实现IOC 容器的。



 一,Spring容器的核心规范


            先上源码:


public interface BeanFactory {

	/**
	 * Used to dereference a FactoryBean and distinguish it from beans
	 * <i>created</i> by the FactoryBean. For example, if the bean named
	 * <code>myEjb</code> is a FactoryBean, getting <code>&myEjb</code> 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 given bean name.
	 * This method allows a Spring BeanFactory to be used as a replacement for the
	 * Singleton or Prototype design pattern.
	 * <p>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 return
	 * @return the 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 (possibly shared or independent) of the given bean name.
	 * <p>Behaves the same as getBean(String), but provides a measure of type safety by
	 * throwing a Spring BeansException 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 <code>getBean(String)</code>.
	 * @param name the name of the bean to return
	 * @param requiredType type the bean must match. Can be an interface or superclass
	 * of the actual class, or <code>null</code> for any match. For example, if the value
	 * is <code>Object.class</code>, this method will succeed whatever the class of the
	 * returned instance.
	 * @return an instance of the bean (never <code>null</code>)
	 * @throws BeanNotOfRequiredTypeException if the bean is not of the required type
	 * @throws NoSuchBeanDefinitionException if there's no such bean definition
	 * @throws BeansException if the bean could not be created
	 */
	Object getBean(String name, Class requiredType) throws BeansException;

	/**
	 * Does this bean factory contain a bean definition with the given name?
	 * <p>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 a bean with the given name is defined
	 */
	boolean containsBean(String name);

	/**
	 * Is this bean a singleton? That is, will <code>getBean</code> always return the same object?
	 * <p>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 is this bean a singleton
	 * @throws NoSuchBeanDefinitionException if there is no bean with the given name
	 * @see #getBean
	 */
	boolean isSingleton(String name) throws NoSuchBeanDefinitionException;

	/**
	 * Determine the type of the bean with the given name.
	 * More specifically, checks the type of object that <code>getBean</code> would return.
	 * For a FactoryBean, returns the type of object that the FactoryBean creates.
	 * @param name the name of the bean to query
	 * @return the type of the bean, or <code>null</code> if not determinable
	 * @throws NoSuchBeanDefinitionException if there is no bean with the given name
	 * @since 1.1.2
	 * @see #getBean
	 * @see FactoryBean#getObjectType()
	 */
	Class getType(String name) throws NoSuchBeanDefinitionException;

	/**
	 * Return the aliases for the given bean name, if defined.
	 * <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
	 */
	String[] getAliases(String name);

}


           上面一段是从spring源码里面拽出来的,在BeanFactory里面,定义了Spring容器最基本的规范,下面我们来依次讲解下各个方法:

   

         1,String FACTORY_BEAN_PREFIX = "&";


                       对FactoryBean的转义定义,因为如果使用bean的名字检索FactoryBean得到的对象是工厂生成的对象,如果需要得到工厂本身,需要转义;例如:myEjb是一个FactoryBean,&myEjb将会得到一个工厂,而不是工厂返回的实例。

           关于BeanFacoty与FactoryBean: BeanFactory是个Factory,也就是IOC容器或对象工厂,FactoryBean是个Bean。在Spring中,所有的Bean都是由BeanFactory(也就是IOC容器)来进行管理的。但对FactoryBean而言,这个Bean不是简单的Bean,而是一个能生产或者修饰对象生成的工厂Bean,它的实现与设计模式中的工厂模式和修饰器模式类似。(from :http://chenzehe.iteye.com/blog/1481476)


          可以看出FactoryBean主要是为了简化复杂bean的装配而产生的。


          2,Object getBean(String name) throws BeansException;


                         根据bean的名字,获取在IOC容器中得到bean实例


        3,Object getBean(String name, Class requiredType) throws BeansException;



                      根据了bean的名字和类型来获取bean实例,比上个方法多了类型条件验证,增强了类型安全验证机制。



        4,boolean containsBean(String name);



                         根据名称查找是否容器中含有这个bean


        5,boolean isSingleton(String name) throws NoSuchBeanDefinitionException;


                      判断bean是否为单例的。


        6,Class getType(String name) throws NoSuchBeanDefinitionException;



                       得到bean类型的类类型,可能会抛出类不存在的异常。

       


         7,String[] getAliases(String name);



              得到bean的别名,如果根据别名检索,那么其原名也会被检索出来。



二,从ClassPathXmlApplicationContext到BeanFactory



            BeanFactory只是定义了容器的规范,spring为容器的实现提供了很多实现类,先来看看我们代码里面,从ClassPathXmlApplicationContext到BeanFactory经历了多少级:



         

         ClassPathXmlApplication虽然提供了好几个构造函数,但是,最终还是会调用:


               

	public ClassPathXmlApplicationContext(String[] paths, Class clazz, ApplicationContext parent)
			throws BeansException {

		super(parent);
		Assert.notNull(paths, "Path array must not be null");
		Assert.notNull(clazz, "Class argument must not be null");
		this.configResources = new Resource[paths.length];
		for (int i = 0; i < paths.length; i++) {
			this.configResources[i] = new ClassPathResource(paths[i], clazz);
		}
		refresh();
	}



            构造函数里面,主要就是调用父类的构造函数,然后我们沿着继承链找:


       

        

       之后的代码估计是加在配置资源,接着是refresh方法,这个方法的真正实现在AbstractApplicationContext这个抽象类中:

          

/*创建 BeanFactory 工厂的过程
		refresh是一个刷新配置的过程,如果Context有可更新的子类,
		当BeanFactory已存在就可更新,如果没有就新创建
*/
public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			this.startupTime = System.currentTimeMillis();

			synchronized (this.activeMonitor) {
				this.active = true;
			}

			//准备刷新上下文环境
			refreshBeanFactory();

			//初始化beanFactory,并进行配置文件的读取
			ConfigurableListableBeanFactory beanFactory = getBeanFactory();

			// Tell the internal bean factory to use the context's class loader.
			beanFactory.setBeanClassLoader(getClassLoader());

			// Populate the bean factory with context-specific resource editors.
			beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this));

			// Configure the bean factory with context semantics.
			beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
			beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
			beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
			beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
			beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

			// 子类覆盖方法做额外处理
			postProcessBeanFactory(beanFactory);

			// Invoke factory processors registered with the context instance.
			for (Iterator it = getBeanFactoryPostProcessors().iterator(); it.hasNext();) {
				BeanFactoryPostProcessor factoryProcessor = (BeanFactoryPostProcessor) it.next();
				factoryProcessor.postProcessBeanFactory(beanFactory);
			}

			if (logger.isInfoEnabled()) {
				if (getBeanDefinitionCount() == 0) {
					logger.info("No beans defined in application context [" + getDisplayName() + "]");
				}
				else {
					logger.info(getBeanDefinitionCount() + " beans defined in application context [" + getDisplayName() + "]");
				}
			}

			try {
				// 激活各种BeanFactory处理器
				invokeBeanFactoryPostProcessors();

				// 注册拦截Bean创建的Bean处理器,这里只是注册,真正调用是在getBean的时候
				registerBeanPostProcessors();

				// 为上下文初始化Message源,即不同语言的消息体,国际化处理
				initMessageSource();

				// 初始化应用消息广播器,并放入“applicationEventMulticaster”bean中
				/*用户可以在配置文件中为容器定义一个自定义的事件广播器,只要实现ApplicationEventMulticaster就可以了,Spring会通过 反射的机制将其注册成容器的事件广播器,如果没有找到配置的外部事件广播器,Spring自动使用 SimpleApplicationEventMulticaster作为事件广播器。*/
				initApplicationEventMulticaster();

				// 留给子类来初始化其他bean
				onRefresh();

				// 在所有注册的bean中查找Listener bean,注册到消息广播器中
				/* Spring根据反射机制,使用ListableBeanFactory的getBeansOfType方法,从BeanDefinitionRegistry中找出所有实现 org.springframework.context.ApplicationListener的Bean,将它们注册为容器的事件监听器,实际的操作就是将其添加到事件广播器所提供的监听器注册表中。*/
				registerListeners();

				// Instantiate singletons this late to allow them to access the message source.
				beanFactory.preInstantiateSingletons();

				// 最后一步:发布事件
				/*在AbstractApplicationContext的publishEvent方法中, Spring委托ApplicationEventMulticaster将事件通知给所有的事件监听器*/
				publishEvent(new ContextRefreshedEvent(this));
			}

			catch (BeansException ex) {
				// Destroy already created singletons to avoid dangling resources.
				beanFactory.destroySingletons();
				throw ex;
			}
		}
	}


           刚开始扒源码,感觉挺杂乱的,画画图什么的还是挺有帮助的,昨天就是在一直跟断点,看看要实现我的getBean都走了哪些代码,今天会从整体结构上先看看。





目录
相关文章
|
2月前
|
负载均衡 监控 Java
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
本文详细介绍了 Spring Cloud Gateway 的核心功能与实践配置。首先讲解了网关模块的创建流程,包括依赖引入(gateway、nacos 服务发现、负载均衡)、端口与服务发现配置,以及路由规则的设置(需注意路径前缀重复与优先级 order)。接着深入解析路由断言,涵盖 After、Before、Path 等 12 种内置断言的参数、作用及配置示例,并说明了自定义断言的实现方法。随后重点阐述过滤器机制,区分路由过滤器(如 AddRequestHeader、RewritePath、RequestRateLimiter 等)与全局过滤器的作用范围与配置方式,提
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
|
2月前
|
缓存 安全 Java
Spring Security通用权限管理模型解析
Spring Security作为Spring生态的核心安全框架,结合RBAC与ACL权限模型,基于IoC与AOP构建灵活、可扩展的企业级权限控制体系,涵盖认证、授权流程及数据库设计、性能优化等实现策略。
237 0
|
2月前
|
缓存 安全 Java
Spring Security权限管理解析
Spring Security是Spring生态中的核心安全框架,采用认证与授权分离架构,提供高度可定制的权限管理方案。其基于过滤器链实现认证流程,通过SecurityContextHolder管理用户状态,并结合RBAC模型与动态权限决策,支持细粒度访问控制。通过扩展点如自定义投票器、注解式校验与前端标签,可灵活适配多租户、API网关等复杂场景。结合缓存优化与无状态设计,适用于高并发与前后端分离架构。
257 0
|
2月前
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
|
2月前
|
SQL Java 数据库连接
Spring Data JPA 技术深度解析与应用指南
本文档全面介绍 Spring Data JPA 的核心概念、技术原理和实际应用。作为 Spring 生态系统中数据访问层的关键组件,Spring Data JPA 极大简化了 Java 持久层开发。本文将深入探讨其架构设计、核心接口、查询派生机制、事务管理以及与 Spring 框架的集成方式,并通过实际示例展示如何高效地使用这一技术。本文档约1500字,适合有一定 Spring 和 JPA 基础的开发者阅读。
328 0
|
1月前
|
XML Java 数据格式
《深入理解Spring》:AOP面向切面编程深度解析
Spring AOP通过代理模式实现面向切面编程,将日志、事务等横切关注点与业务逻辑分离。支持注解、XML和编程式配置,提供五种通知类型及丰富切点表达式,助力构建高内聚、低耦合的可维护系统。
|
1月前
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
2月前
|
Java 数据库 数据安全/隐私保护
Spring Boot四层架构深度解析
本文详解Spring Boot四层架构(Controller-Service-DAO-Database)的核心思想与实战应用,涵盖职责划分、代码结构、依赖注入、事务管理及常见问题解决方案,助力构建高内聚、低耦合的企业级应用。
796 1
|
2月前
|
Kubernetes Java 微服务
Spring Cloud 微服务架构技术解析与实践指南
本文档全面介绍 Spring Cloud 微服务架构的核心组件、设计理念和实现方案。作为构建分布式系统的综合工具箱,Spring Cloud 为微服务架构提供了服务发现、配置管理、负载均衡、熔断器等关键功能的标准化实现。本文将深入探讨其核心组件的工作原理、集成方式以及在实际项目中的最佳实践,帮助开发者构建高可用、可扩展的分布式系统。
419 0

推荐镜像

更多
  • DNS