Spring 5 IOC 容器源码分析

博主记录Spring源码学习历程,采用5.1.6.BUILD - SNAPSHOT版本。介绍Spring两大核心组件IOC和AOP,重点分析Spring IoC容器,以ClassPathXmlApplicationContext为例分析容器创建过程,给出获取bean的简单示例及调试代码的方法,还提供了参考资料。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring 两大核心组件 IOC和Aop,如果有说错的地方请一定不吝指出,相互学习, 随便记录下自己的学习 Spring  源码学习历程 

本次采用的源码版本是 5.1.6.BUILD-SNAPSHOT

 源码构建请参考(https://blog.youkuaiyun.com/str0708/article/details/88539365)文章

1 Spring IoC 简洁

ApplicationContext接口代表Spring IoC容器,负责实例化,配置和组装bean,ApplicationContextSpring提供了几种接口实现。在独立应用程序中,通常会创建一个ClassPathXmlApplicationContext 或者FileSystemXmlApplicationContext,

ClassPathXmlApplicationContext和FileSystemXmlApplicationContext都是同时继承AbstractXmlApplicationContext。

先从ClassPathXmlApplicationContext作为Spring IOC 容器,从 ClassPathXmlApplication 分析容器创建的过程,首先来看一下ClassPathXmlApplicationContext的依赖关系:

我先创建一个新项目,好方便调试对应的 IOC源码

ApplicationContext 大概继承结构

下面我先用ClassPathXmlApplicationContext获取ApplicationContext实例
创建一个测试类 如下

package com.demo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author 疯信子
 * @version 1.0
 * @date 2019/3/14.
 */
public class ApplicationContextDemo {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationfile.xml");

		MessageService messageService = context.getBean("messageService", MessageService.class);
		System.out.println(messageService.getMessage());
	}
}

 

在spring-context中创建applicationfile.xml

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



	<bean id="messageService" class="com.demo.MessageServiceImpl"/>
</beans>

以上就是最简单的获取bean的例子。

然后就可以具体调试代码。bean 的初始化

参考资料:

https://docs.spring.io/spring/docs/5.1.6.BUILD-SNAPSHOT/spring-framework-reference/core.html#spring-core 

https://javadoop.com/post/spring-ioc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值