Spring源码分析 手写简单IOC容器
Spring的两大特性就是IOC和AOP。
IOC Container,控制反转容器,通过读取配置文件或注解,将对象封装成Bean存入IOC容器待用,程序需要时再从容器中取,实现控制权由程序员向程序的转变。
一、代码结构
二、注解扫描
1、新建OrderService、UserService、Test类用于模拟实际开发
@Component("orderService")
@Scope("prototype")
public class OrderService implements BeanNameAware {
@Autowired
private UserService userService;
public void test() {
System.out.println(userService);
}
public void setBeanName(String name) {
this.beanName = beanName;
}
}
@Component("userService")
public class UserService {
}
public class Test {
public static void main(String[] args) {
//对应AnnotationConfigApplicationContext
//扫描 (判断是否存在Component) + 实例化(Bean的生命周期:1、实例化 2、依赖注入)
CustomApplicationContext customApplicationContext = new CustomApplicationContext(AppConfig.class);
Object userService1 = customApplicationContext.getBean("orderService");
System.out.println(userService);
System.out.println(userService1);
}
}
2、新建注解Component、ComponentScan、Autowired、Scope
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Component { // 用于将类注册成Bean
String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ComponentScan { //用于配置类扫描的包
String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD})
public @interface Autowired { //属性注入
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Scope { //bean的范围
String value() default "singleton";
}
3、定义CustomApplicationContext实现注解扫描
- 对应Spring的AnnotationConfigApplicationContext,通过传入配置文件对象,读取ComponentScan的Value进行包扫描,扫描后获取带@Component注解的类
public class CustomApplicationContext {
private Class configClass;
public CustomApplicationContext(Class configClass) {
this.configClass = configClass;
//扫描(判断类上是否存在Component)(class文件) --> 形成beanDefinition
List<Class> classList = scan(configClass);
}
private List<Class> scan(Class configClass) {
List<Class> list = new ArrayList<Class>();
//存在注解,通过value获取要扫描包路径
if (configClass.isAnnotationPresent(ComponentScan.class)){
ComponentScan componentScan = (ComponentScan)configClass.getAnnotation(ComponentScan.class);
String path = componentScan.value();
path = path.replace(".","/"); //包转化为包路径(com.gg.service)
//扫描path路径下到类
ClassLoader classLoader = CustomApplicationContext.class.getClassLoader();
// 利用类加载器,根据包路径获取URL/target/classes/com/gg/service
URL resource = classLoader.getResource(path);
File file = new File(resource.getFile());
if (file.isDirectory()) {
for (File f: file.listFiles()){
String absolutePath = f.getAbsolutePath(); //类的完整路径
absolutePath = absolutePath.substring(absolutePath.indexOf("com"),absolutePath.indexOf(".class"));
absolutePath = absolutePath.replace("/",".");
//com.gg.service.userService
Class clazz = null;
try {
clazz = classLoader.loadClass(absolutePath);
// 存在注解,将类加入数组
if (clazz.isAnnotationPresent(Component.class)) {
list.add(clazz);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
return list;
}
}
4、将扫描获得的类封装成beanDefinition
- 扫描得到的类,将beanName、类型、类的范围封装成beanDefinition
- getBean时不用重新扫描,直接冲beanDefinitionMap获取
private Map<String,BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>();
public CustomApplicationContext(Class configClass) {
this.configClass = configClass;
List<Class> classList = scan(configClass); //扫描得到class
for (Class clazz: classList){
Component component = (Component) clazz.getAnnotation(Component.class);
String beanName = component.value();
BeanDefinition beanDefinition = new BeanDefinition();
if (clazz.isAnnotationPresent(Scope.class)){
Scope scope = (Scope) clazz.getAnnotation(Scope.class);
beanDefinition.setScope(scope.value());
}else{
beanDefinition.setScope("singleton");//默认为单例
}
beanDefinition.setBeanClass(clazz);
beanDefinitionMap.put(beanName,beanDefinition);
}
public class BeanDefinition { //bean的定义
private String scope;
private Class beanClass;
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public Class getBeanClass() {
return beanClass;
}
public void setBeanClass(Class beanClass) {
this.beanClass = beanClass;
}
}
- 至此,我们通过新建CustomApplicationContext,将添加注解的类加入到beanDefinitionMap。
三、实例化Bean
1、单例类先实例化,存入单例池
- 从beanDefinitionMap取出BeanDefinition,对单例类调用createBean()实例化,添加到单例池
private Map<String,Object> singletonPool = new ConcurrentHashMap<String, Object>();
public CustomApplicationContext(Class configClass) {
this.configClass = configClass;
//扫描将注解的类存入beanDefinitionMap
List<Class> classList = scan(configClass);
for (Class clazz: classList){
Component component = (Component) clazz.getAnnotation(Component.class);
String beanName = component.value();
BeanDefinition beanDefinition = new BeanDefinition();
if (clazz.isAnnotationPresent(Scope.class)){
Scope scope = (Scope) clazz.getAnnotation(Scope.class);
beanDefinition.setScope(scope.value());
}else{
beanDefinition.setScope("singleton");
}
beanDefinition.setBeanClass(clazz);
beanDefinitionMap.put(beanName,beanDefinition);
}
//将单例类添加到单例池singletonPool
for (String beanName : beanDefinitionMap.keySet()){
BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
if (beanDefinition.getScope().equals("singleton")){
//实例化bean
Object bean = createBean(beanName,beanDefinition);
singletonPool.put(beanName,bean);
}
}
}
private Object createBean(String beanName,BeanDefinition beanDefinition) {
//实例化、填充属性、Aware、初始化
Class beanClass = beanDefinition.getBeanClass();
try {
// 从beanDefinition中获取类型,并实例化
Object bean = beanClass.getDeclaredConstructor().newInstance();
//属性填充
Field[] fields = beanClass.getDeclaredFields(); //DeclaredFields 所有属性
for(Field field: fields){
if (field.isAnnotationPresent(Autowired.class)){
Object annotationField = getBean(field.getName());
field.setAccessible(true); //反射产生对象要打开权限
field.set(bean,annotationField);
}
}
// Aware
if (bean instanceof BeanNameAware){
((BeanNameAware)bean).setBeanName(beanName); //实现该端口就调用此方法
}
// 初始化
if (bean instanceof InitializingBean){
((InitializingBean)bean).afterPropertiesSet(); //实现该端口就调用此方法
}
return bean;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
- 新建BeanNameAware、InitializingBean接口,实例类时,通过判断是否实现该接口,在实例初始化时
public interface BeanNameAware {
public void setBeanName(String name);
}
public interface InitializingBean {
public void afterPropertiesSet();
}
- 通过调用createBean()实例化beanDefinition中的类,单例在启动时实例,原型在调用getBean()再实例
2、getBean()
public Object getBean(String beanName){
BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
if (beanDefinition.getScope().equals("prototype")){
return createBean(beanName,beanDefinition);
}else{
Object bean = singletonPool.get(beanName);
if (bean == null){
Object newBean = createBean(beanName,beanDefinition);
singletonPool.put(beanName,newBean);
return newBean;
}
return bean;
}
}
Spring源码分析 手写简单IOC容器的更多相关文章
- Spring源码分析之-加载IOC容器
本文接上一篇文章 SpringIOC 源码,控制反转前的处理(https://mp.weixin.qq.com/s/9RbVP2ZQVx9-vKngqndW1w) 继续进行下面的分析 首先贴出 Spr ...
- 源码分析 | 手写mybait-spring核心功能(干货好文一次学会工厂bean、类代理、bean注册的使用)
作者:小傅哥 博客:https://bugstack.cn - 汇总系列原创专题文章 沉淀.分享.成长,让自己和他人都能有所收获! 一.前言介绍 一个知识点的学习过程基本分为:运行helloworld ...
- 面试必会之ArrayList源码分析&手写ArrayList
简介 ArrayList是我们开发中非常常用的数据存储容器之一,其底层是数组实现的,我们可以在集合中存储任意类型的数据,ArrayList是线程不安全的,非常适合用于对元素进行查找,效率非常高. 线程 ...
- spring源码分析之玩转ioc:bean初始化和依赖注入(一)
最近赶项目,天天加班到十一二点,终于把文档和代码都整完了,接上继续整. 上一篇聊了beanProcess的注册以及对bean的自定义修改和添加,也标志着创建bean的准备工作都做好了,接下来就是开大招 ...
- Spring源码 20 手写模拟源码
参考源 https://www.bilibili.com/video/BV1tR4y1F75R?spm_id_from=333.337.search-card.all.click https://ww ...
- Spring源码分析(十九)容器的功能扩展概览
摘要: 本文结合<Spring源码深度解析>来分析Spring 5.0.6版本的源代码.若有描述错误之处,欢迎指正. 经过前面几章的分析,相信大家已经对 Spring 中的容器功能有了简单 ...
- 《四 spring源码》手写springmvc
手写SpringMVC思路 1.web.xml加载 为了读取web.xml中的配置,我们用到ServletConfig这个类,它代表当前Servlet在web.xml中的配置信息.通过web.xml ...
- 《四 spring源码》手写springioc框架
手写SpringIOCXML版本 /** * 手写Spring专题 XML方式注入bean * * * */ public class ClassPathXmlApplicationContext { ...
- spring源码分析系列3:BeanFactory核心容器的研究
目录 @(spring源码分析系列3:核心容器的研究) 在讲容器之前,再明确一下知识点. BeanDefinition是Bean在容器的描述.BeanDefinition与Bean不是一个东西. Be ...
随机推荐
- Pytest单元测试框架:插件-allure-pytest环境搭建并在本地生成一个测试报告
之前写了allure-pytest的官方文档啃的内容,有些交流的朋友,实践起来没什么头绪,所以就有了这篇文章,也给自己填个坑 第一步:搭建Allure.JDK环境 1. 搭建JDK环境 不装jdk你会 ...
- 44-final, finally, finalize的区别
final—修饰符(关键字) 如果一个类被声明为final,意味着它不能再派生出新的子类,不能作为父类被继承. 因此一个类不能既被声明为 abstract的,又被声明为final的.将变量或方法声明为 ...
- demo3同通讯录展示的方式分组排序
按A-Z顺序分组展示 有些项目中会需要这样的需求.形成类似于上述的界面.类似于通讯录里边的排序.实现的效果:所有的数据展示的时候,能够分组展示.顺序按照A-Z的书序进行排列.如果不是以A-Z开头,则默 ...
- elasticsearch 高级搜索示例 es7.0
基础数据 创建索引 PUT mytest { "mappings": { "properties": { "title": { " ...
- ubuntu apt-get 安装找不到包问题
1.首先 sudo gedit /etc/apt/sources.list 删除全部换成国内源 (推荐163) 2.考虑 ubuntu apt-get update失败 1.出现错误:E:Could ...
- Devops 原始思想 所要实现的目标
解释: DevOps(Development和Operations的组合词)是一组过程.方法与系统的统称,用于促进开发(应用程序/软件工程).技术运营和质量保障(QA)部门之间的沟通.协作与整合. 它 ...
- 14、Java文件操作stream、File、IO
1.文件操作涉及到的基本概念 File File类 是文件操作的主要对象中文意义就是 文件 顾名思意 万物皆文件,在计算上看到的所有东西都是文件保存,不管是你的图片.视频.数据库数据等等都是按照基本的 ...
- 【Python笔记】2020年7月30日练习【汉诺塔游戏】
学习教程:廖雪峰-Python教程-函数-递归函数 学习笔记: 实例代码如下: def move(n, a, b, c): if n == 1: print(a,'--->', c) else: ...
- 07 CentOS简单命令与XShell简单使用
关机 poweroff 重启 init 6 查看ip地址 ifconfig 查看当前目录下的文件与目录 ls ll 判断命令是内部还是外部的类型 type ifconfig 通过file /sbin/ ...
- Flutter 容器Container类和布局Layout类
1.布局和容器 [布局]是把[容器]按照不同的方式排列起来. Scaffold包含的主要部门:appBar,body,bottomNavigator 其中body可以是一个布局组件,也可以是一个容器组 ...