Spring源码 20 手写模拟
项目地址
https://gitee.com/liao-hang/hand-write-spring.git
模拟 Spring
注解
自动装配
Autowired
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Autowired {
}
组件
Component
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {
String value() default "";
}
组件扫描
ComponentScan
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ComponentScan {
String value() default "";
}
范围
Scope
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Scope {
String value() default "";
}
Bean 定义信息
BeanDefinition
public class BeanDefinition {
/**
* 类型
*/
private Class type;
/**
* 范围
*/
private String scope;
public Class getType() {
return type;
}
public void setType(Class type) {
this.type = type;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
}
Bean 名称感知
BeanNameAware
public interface BeanNameAware {
/**
* 设置 Bean 名称
* @param beanName Bean名称
*/
void setBeanName(String beanName);
}
Bean 后置处理器
BeanPostProcessor
public interface BeanPostProcessor {
/**
* 初始化前
* @param beanName Bean名称
* @param bean Bean对象
* @return
*/
Object postProcessBeforeInitialization(String beanName, Object bean);
/**
* 初始化后
* @param beanName Bean名称
* @param bean Bean对象
* @return
*/
Object postProcessAfterInitialization(String beanName, Object bean);
}
初始化 Bean
InitializationBean
public interface InitializationBean {
/**
* 属性设置后
*/
void afterPropertiesSet();
}
注解配置应用上下文
AnnotationConfigApplicationContext
public class AnnotationConfigApplicationContext {
/**
* 配置的类
*/
private Class configClass;
/**
* Bean 后置处理器列表
*/
private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();
/**
* Bean 定义信息池
*/
private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
/**
* 单例池
*/
private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();
public AnnotationConfigApplicationContext(Class configClass) {
this.configClass = configClass;
/*
扫描 -> BeanDefinition -> beanDefinitionMap
*/
// 是否有 @ComponentScan 注解
if (configClass.isAnnotationPresent(ComponentScan.class)) {
ComponentScan componentScan = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
// 注解中的路径
String path = componentScan.value();
// 处理路径
path = path.replace(".", "/");
// 类加载器
ClassLoader classLoader = AnnotationConfigApplicationContext.class.getClassLoader();
// 资源
URL resource = classLoader.getResource(path);
// 文件
File file = new File(resource.getFile());
// 如果为目录
if (file.isDirectory()) {
// 文件列表
File[] files = file.listFiles();
for (File f : files) {
// 绝对路径
String fileName = f.getAbsolutePath();
// 是否为 class 文件
if (fileName.endsWith(".class")) {
// 类名 cn\sail\test\文件名
String className = fileName.substring(fileName.indexOf("cn"), fileName.indexOf(".class"));
// 处理路径
className = className.replace("\\", ".");
try {
Class<?> clazz = classLoader.loadClass(className);
// 是否有 @Component 注解
if (clazz.isAnnotationPresent(Component.class)) {
// 接口和类是否相同或者是否为其超类或超接口
if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
BeanPostProcessor instance = (BeanPostProcessor) clazz.newInstance();
beanPostProcessorList.add(instance);
}
Component component = clazz.getAnnotation(Component.class);
String beanName = component.value();
if ("".equals(beanName)) {
beanName = Introspector.decapitalize(clazz.getSimpleName());
}
BeanDefinition beanDefinition = new BeanDefinition();
beanDefinition.setType(clazz);
// 是否有 @Scope 注解
if (clazz.isAnnotationPresent(Scope.class)) {
// 如果有,以传入的模式为准
Scope scope = clazz.getAnnotation(Scope.class);
beanDefinition.setScope(scope.value());
} else {
// 如果没有,默认为单例模式
beanDefinition.setScope("singleton");
}
beanDefinitionMap.put(beanName, beanDefinition);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
// 实例化单例 Bean
for (String beanName : beanDefinitionMap.keySet()) {
BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
// 如果为单例模式,将 BeanDefinition 放入单例池中,下次直接从池中取,以保证单例
if ("singleton".equals(beanDefinition.getScope())) {
Object bean = createBean(beanName, beanDefinition);
singletonObjects.put(beanName, bean);
}
}
}
/**
* 创建 Bean
* @param beanName Bean 名称
* @param beanDefinition Bean 定义信息
* @return Bean 对象
*/
private Object createBean(String beanName, BeanDefinition beanDefinition) {
Class clazz = beanDefinition.getType();
try {
Object instance = clazz.getConstructor().newInstance();
// 依赖注入
for (Field f : clazz.getDeclaredFields()) {
// 是否有 @Autowired 注解
if (f.isAnnotationPresent(Autowired.class)) {
// 忽略访问修饰符限制
f.setAccessible(true);
// 注入
f.set(instance, getBean(f.getName()));
}
}
// Aware
if (instance instanceof BeanNameAware) {
((BeanNameAware) instance).setBeanName(beanName);
}
// 初始化前
for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
instance = beanPostProcessor.postProcessBeforeInitialization(beanName, instance);
}
// 初始化
if (instance instanceof InitializationBean) {
((InitializationBean) instance).afterPropertiesSet();
}
// 初始化后
for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
instance = beanPostProcessor.postProcessAfterInitialization(beanName, instance);
}
return instance;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
public Object getBean(String beanName) {
BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
if (beanDefinition == null) {
throw new NullPointerException();
} else {
String scope = beanDefinition.getScope();
if ("singleton".equals(scope)) {
Object bean = singletonObjects.get(beanName);
// 如果单例池中没有对应 Bean,创建 Bean 后再放入池中
if (bean == null) {
bean = createBean(beanName, beanDefinition);
singletonObjects.put(beanName, bean);
}
return bean;
} else {
// 如果不是单例模式,直接创建 Bean
return createBean(beanName, beanDefinition);
}
}
}
}
使用 Spring
应用配置
AppConfig
@ComponentScan("cn.sail.test")
public class AppConfig {
}
用户服务
UserInterface
public interface UserInterface {
/**
* 测试
*/
void test();
}
用户服务实现类
UserService
@Component
public class UserService implements UserInterface{
@Autowired
private OrderService orderService;
@Override
public void test() {
System.out.println(orderService);
}
}
排序服务
OrderService
@Component
public class OrderService {
}
Bean 后置处理器
MyBeanPostProcessor
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
/**
* 初始化前
*
* @param beanName
* @param bean
* @return
*/
@Override
public Object postProcessBeforeInitialization(String beanName, Object bean) {
if ("userService".equals(beanName)) {
System.out.println("1111");
}
return bean;
}
/**
* 初始化后
*
* @param beanName
* @param bean
* @return
*/
@Override
public Object postProcessAfterInitialization(String beanName, Object bean) {
if ("userService".equals(beanName)) {
Object proxyInstance = Proxy.newProxyInstance(MyBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("切面逻辑");
return method.invoke(bean, args);
}
});
return proxyInstance;
}
return bean;
}
}
测试
Test
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
UserInterface userService = (UserInterface) applicationContext.getBean("userService");
userService.test();
}
}
参考
https://www.bilibili.com/video/BV1tR4y1F75R?spm_id_from=333.337.search-card.all.click
https://www.bilibili.com/video/BV12Z4y197MU?spm_id_from=333.999.0.0
《Spring源码深度解析(第2版)》
版本
Spring 5.3.15
Spring源码 20 手写模拟的更多相关文章
- Spring源码 20 手写模拟源码
参考源 https://www.bilibili.com/video/BV1tR4y1F75R?spm_id_from=333.337.search-card.all.click https://ww ...
- 《四 spring源码》手写springioc框架
手写SpringIOCXML版本 /** * 手写Spring专题 XML方式注入bean * * * */ public class ClassPathXmlApplicationContext { ...
- 《四 spring源码》手写springmvc
手写SpringMVC思路 1.web.xml加载 为了读取web.xml中的配置,我们用到ServletConfig这个类,它代表当前Servlet在web.xml中的配置信息.通过web.xml ...
- Spring源码分析 手写简单IOC容器
Spring的两大特性就是IOC和AOP. IOC Container,控制反转容器,通过读取配置文件或注解,将对象封装成Bean存入IOC容器待用,程序需要时再从容器中取,实现控制权由程序员向程序的 ...
- 源码分析 | 手写mybait-spring核心功能(干货好文一次学会工厂bean、类代理、bean注册的使用)
作者:小傅哥 博客:https://bugstack.cn - 汇总系列原创专题文章 沉淀.分享.成长,让自己和他人都能有所收获! 一.前言介绍 一个知识点的学习过程基本分为:运行helloworld ...
- 面试必会之ArrayList源码分析&手写ArrayList
简介 ArrayList是我们开发中非常常用的数据存储容器之一,其底层是数组实现的,我们可以在集合中存储任意类型的数据,ArrayList是线程不安全的,非常适合用于对元素进行查找,效率非常高. 线程 ...
- Spring源码试读--BeanFactory模拟实现
动机 现在Springboot越来越便捷,如果简单的Spring应用,已无需再配置xml文件,基本可以实现全注解,即使是SpringCloud的那套东西,也都可以通过yaml配置完成.最近一年一直在用 ...
- Spring源码学习之:模拟实现BeanFactory,从而说明IOC容器的大致原理
spring的IOC容器能够帮我们自动new对象,对象交给spring管之后我们不用自己手动去new对象了.那么它的原理是什么呢?是怎么实现的呢?下面我来简单的模拟一下spring的机制,相信看完之后 ...
- 框架源码系列十二:Mybatis源码之手写Mybatis
一.需求分析 1.Mybatis是什么? 一个半自动化的orm框架(Object Relation Mapping). 2.Mybatis完成什么工作? 在面向对象编程中,我们操作的都是对象,Myba ...
- MVVM模式源码分析手写实现
1.demo1.html <!DOCTYPE html> <html lang="en"> <head> <meta charset=&q ...
随机推荐
- 【LeetCode回溯算法#05】分割回文串(复习双指针判断回文以及substr函数使用记录)
分割回文串 力扣题目链接 给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 .返回 s 所有可能的分割方案. 回文串 是正着读和反着读都一样的字符串. 示例 1: 输入:s = ...
- MySQL 数据库死锁排查
死锁排查方法 查看进程状态 show processlist; 查看行锁的状态 show status like 'InnoDB_row_lock%'; 查询是否有死锁 show engine inn ...
- 【Azure 事件中心】Azure Event Hub客户端遇见 Expired Heartbeat 错误
问题描述 Azure Event Hub 在消费数端中,经常性遇见 Expired Heartbeat 错误 (consumer-xxxxxxxxxxxxx-c84873c6c828e8df6c843 ...
- 【Azure 存储服务】关于Storage Account Queue使用的几个问题
1) 在消费Storage Queue中的数据的时候,如何只过滤出 Subject 为"message/{messageid}"这种,去掉subject为"informa ...
- [MAUI] 混合开发概念
混合开发的概念是相对与原生开发来说的:App不直接运行原生程序,而是在原生程序中运行一个Web程序,原生程序中包含Web运行时,用于承载Web页面.暂且将原生应用称之为Web容器,Web容器应该能 ...
- C#移除List中特定元素
在List里面移除其中一个元素之后,原有的索引以及索引对应的值会发生改变,如果按照原有的索引值删除,就会误删除其它元素. 1.实现思路 原始List为A,将需要删除的元素放到一个List B里面,遍历 ...
- USB数据传输与手机授权:充电宝常规使用不需要授权
概述 此篇为解答充电宝骗局问题,骗局概述:两个人做局,以充测试充电宝是否损坏为由,插到受骗者手机上,受骗者允许了手机弹出的授权请求后,偷偷将病毒注入手机. Q:什么情况下手机会弹出授权? A:手机用数 ...
- IP对讲广播音频模块解决方案
需求分析 随着数字化进程的不断推进,对讲已经覆盖到了各行业各业.并且也逐渐呈现出场景分散化的特点.鉴于此,团队根据市场的变化,及时推出了一款标准化的模块,方便系统集成厂商集成和运用,从而达到节省开 ...
- 从一线方案商的角度来看高通QCC3020芯片
写在前面的话 QCC3020的推出已经有一段时间了.在蓝牙音频的圈子里,属于家喻户晓的芯片了.再加上高通的大力宣传和一些顶尖级产品的使用,可以说,它是高通在吸收CSR的技术之后,着力推出的最具竞争 ...
- 三维模型3DTile格式轻量化压缩处理的数据质量提升方法分析
三维模型3DTile格式轻量化压缩处理的数据质量提升方法分析 在处理三维模型3DTile格式的轻量化压缩时,如何在减少数据量的同时,保证或提升数据质量是一大挑战.以下为一些提升数据质量的方法分析: 改 ...