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

本文涉及的产品
云解析 DNS,旗舰版 1个月
全局流量管理 GTM,标准版 1个月
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
简介:          先来看一下我们学习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都走了哪些代码,今天会从整体结构上先看看。





目录
相关文章
|
6天前
|
数据采集 人工智能 Java
1天消化完Spring全家桶文档!DevDocs:一键深度解析开发文档,自动发现子URL并建立图谱
DevDocs是一款基于智能爬虫技术的开源工具,支持1-5层深度网站结构解析,能将技术文档处理时间从数周缩短至几小时,并提供Markdown/JSON格式输出与AI工具无缝集成。
58 1
1天消化完Spring全家桶文档!DevDocs:一键深度解析开发文档,自动发现子URL并建立图谱
|
7天前
|
安全 Java API
深入解析 Spring Security 配置中的 CSRF 启用与 requestMatchers 报错问题
本文深入解析了Spring Security配置中CSRF启用与`requestMatchers`报错的常见问题。针对CSRF,指出默认已启用,无需调用`enable()`,只需移除`disable()`即可恢复。对于`requestMatchers`多路径匹配报错,分析了Spring Security 6.x中方法签名的变化,并提供了三种解决方案:分次调用、自定义匹配器及降级使用`antMatchers()`。最后提醒开发者关注版本兼容性,确保升级平稳过渡。
50 2
|
27天前
|
存储 Java 文件存储
微服务——SpringBoot使用归纳——Spring Boot使用slf4j进行日志记录—— logback.xml 配置文件解析
本文解析了 `logback.xml` 配置文件的详细内容,包括日志输出格式、存储路径、控制台输出及日志级别等关键配置。通过定义 `LOG_PATTERN` 和 `FILE_PATH`,设置日志格式与存储路径;利用 `&lt;appender&gt;` 节点配置控制台和文件输出,支持日志滚动策略(如文件大小限制和保存时长);最后通过 `&lt;logger&gt;` 和 `&lt;root&gt;` 定义日志级别与输出方式。此配置适用于精细化管理日志输出,满足不同场景需求。
130 1
|
7天前
|
前端开发 安全 Java
Spring Boot 便利店销售系统项目分包设计解析
本文深入解析了基于Spring Boot的便利店销售系统分包设计,通过清晰的分层架构(表现层、业务逻辑层、数据访问层等)和模块化设计,提升了代码的可维护性、复用性和扩展性。具体分包结构包括`controller`、`service`、`repository`、`entity`、`dto`、`config`和`util`等模块,职责分明,便于团队协作与功能迭代。该设计为复杂企业级应用开发提供了实践参考。
37 0
|
3天前
|
前端开发 Java 物联网
智慧班牌源码,采用Java + Spring Boot后端框架,搭配Vue2前端技术,支持SaaS云部署
智慧班牌系统是一款基于信息化与物联网技术的校园管理工具,集成电子屏显示、人脸识别及数据交互功能,实现班级信息展示、智能考勤与家校互通。系统采用Java + Spring Boot后端框架,搭配Vue2前端技术,支持SaaS云部署与私有化定制。核心功能涵盖信息发布、考勤管理、教务处理及数据分析,助力校园文化建设与教学优化。其综合性和可扩展性有效打破数据孤岛,提升交互体验并降低管理成本,适用于日常教学、考试管理和应急场景,为智慧校园建设提供全面解决方案。
59 14
|
7天前
|
Java 关系型数据库 MySQL
深入解析 @Transactional——Spring 事务管理的核心
本文深入解析了 Spring Boot 中 `@Transactional` 的工作机制、常见陷阱及最佳实践。作为事务管理的核心注解,`@Transactional` 确保数据库操作的原子性,避免数据不一致问题。文章通过示例讲解了其基本用法、默认回滚规则(仅未捕获的运行时异常触发回滚)、因 `try-catch` 或方法访问修饰符不当导致失效的情况,以及数据库引擎对事务的支持要求。最后总结了使用 `@Transactional` 的五大最佳实践,帮助开发者规避常见问题,提升项目稳定性与可靠性。
114 11
|
8天前
|
缓存 安全 Java
深入解析HTTP请求方法:Spring Boot实战与最佳实践
这篇博客结合了HTTP规范、Spring Boot实现和实际工程经验,通过代码示例、对比表格和架构图等方式,系统性地讲解了不同HTTP方法的应用场景和最佳实践。
59 5
|
7天前
|
安全 Java 数据安全/隐私保护
Spring Security: 深入解析 AuthenticationSuccessHandler
本文深入解析了 Spring Security 中的 `AuthenticationSuccessHandler` 接口,它用于处理用户认证成功后的逻辑。通过实现该接口,开发者可自定义页面跳转、日志记录等功能。文章详细讲解了接口方法参数及使用场景,并提供了一个根据用户角色动态跳转页面的示例。结合 Spring Security 配置,展示了如何注册自定义的成功处理器,帮助开发者灵活应对认证后的多样化需求。
40 2
|
7天前
|
前端开发 IDE Java
Spring MVC 中因导入错误的 Model 类报错问题解析
在 Spring MVC 或 Spring Boot 开发中,若导入错误的 `Model` 类(如 `ch.qos.logback.core.model.Model`),会导致无法解析 `addAttribute` 方法的错误。正确类应为 `org.springframework.ui.Model`。此问题通常因 IDE 自动导入错误类引起。解决方法包括:删除错误导入、添加正确包路径、验证依赖及清理缓存。确保代码中正确使用 Spring 提供的 `Model` 接口以实现前后端数据传递。
31 0
|
2月前
|
网络协议 Java Shell
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
113 7

热门文章

最新文章

推荐镜像

更多