当前位置:网站首页>Chapter 2: try to implement a simple bean container
Chapter 2: try to implement a simple bean container
2022-07-05 07:13:00 【Bubble ^ bubble】
The goal is
Spring Bean What is the container ?
Spring Contains and manages the configuration and life cycle of application objects , In this sense, it's a container for hosting objects , You can configure each of your Bean How are objects created , these Bean You can create a single instance or generate a new instance every time you need it , And how they are built and used in relation to each other .
If one Bean Object to Spring Container management , So this Bean Objects should be disassembled and stored in a similar way to parts Bean The definition of , This is equivalent to an operation to decouple objects , Can be Spring Easier to manage , It's like dealing with circular dependencies .
When one Bean After the object is defined and stored , Again by Spring Assemble in a unified way , This process includes Bean The initialization 、 Attribute filling, etc , In the end, we can use one completely Bean The instantiated object .
And our goal in this chapter is to define a simple Spring Containers , Used for definition 、 Storage and access Bean object .
Design
Any specific data structure that can store data is realized , You can call it a container . for example :ArrayList、LinkedList、HashSet etc. , But in Spring Bean In the container scenario , We need a data structure that can be used to store and index names , So choose HashMap It's the most appropriate .
Here is a brief introduction HashMap,HashMap It's based on the perturbation function 、 Load factor 、 Red black tree conversion and other technical content , The zipper addressing data structure formed , It can make the data more hash distributed in the hash bucket and the linked list and red black tree formed during collision . Its data structure will maximize the complexity of the whole data reading O(1) ~ O(Logn) ~O(n) Between , Of course, in extreme cases there will be O(n) Linked list to find more data . But we went through 10 Re addressing verification test of disturbance function for 10000 data , The data will be hashed evenly on each hash bucket index , therefore HashMap Very suitable for Spring Bean On the container implementation of .
Another simple one Spring Bean Container implementation , still need sth. Bean The definition of 、 register 、 Get three basic steps , The simplified design is as follows ;
- Definition :BeanDefinition, Maybe you're looking up Spring A class often seen in source code , For example, it would include singleton、prototype、BeanClassName etc. . But at present, our initial implementation will be more simple , Define only one Object Types are used to hold objects .
- register : This process is equivalent to storing data in HashMap in , Just now HashMap What's stored is defined Bean Object information of .
- obtain : Finally, get the object ,Bean The name of is key,Spring The container is initialized Bean in the future , You can get it directly .
Realization
Engineering structure
Class diagram relation
Spring Bean The whole implementation of the container is very simple , It just includes a simple BeanFactory and BeanDefinition, The class name here is associated with Spring Consistent in the source code , It's just that the current class implementation will be relatively simpler , In the follow-up implementation process and constantly add content .
- BeanDefinition, Used for definition Bean Instantiation information , Now the realization is based on a Object Storage objects
- BeanFactory, On behalf of Bean Object's factory , It can store Bean Define the Map And get .
Bean Definition
package com;
public class BeanDefinition {
private Object bean;
public BeanDefinition(Object bean) {
this.bean = bean;
}
public Object getBean() {
return bean;
}
}
- current Bean In the definition , only one Object To hold Bean object . If you are interested, please refer to Spring Information about this class in the source code , The names are all the same .
- However, it will be gradually improved in the subsequent implementation BeanDefinition Fill in related properties , for example :SCOPE_SINGLETON、SCOPE_PROTOTYPE、ROLE_APPLICATION、ROLE_SUPPORT、ROLE_INFRASTRUCTURE as well as Bean Class Information .
Bean factory
package com;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class BeanFactory {
/** * Bean Containers */
private Map<String,BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
/** * obtain Bean * @param name * @return */
public Object getBean(String name){
return beanDefinitionMap.get(name).getBean();
}
/** * register Bean * @param name * @param beanDefinition */
public void registerBeanDefinition(String name,BeanDefinition beanDefinition){
beanDefinitionMap.put(name,beanDefinition);
}
}
- stay Bean In the realization of the factory , It includes Bean Registration of , It's registered here Bean The definition information of . Also included in this class is getting Bean The operation of .
- current BeanFactory Still a very simplified implementation , But this simplified implementation is also the whole Spring In the container about Bean The final result of use , But the implementation process only shows the basic core principles . In the subsequent supplementary implementation , This is going to get bigger and bigger .
test
package com;
public class UserService {
public void queryUserInfo(){
System.out.println(" Query user information ");
}
}
package com;
import org.junit.Test;
public class UTest
{
@Test
public void test_BeanFactory() {
//1. initialization BeanFactory
BeanFactory beanFactory = new BeanFactory();
//2. Registration Bean
BeanDefinition beanDefinition = new BeanDefinition(new UserService());
beanFactory.registerBeanDefinition("userService",beanDefinition);
//3. obtain Bean
UserService userService = (UserService)beanFactory.getBean("userService");
userService.queryUserInfo();
}
}
边栏推荐
- 并发编程 — 如何中断/停止一个运行中的线程?
- 目标检测系列——Faster R-CNN原理详解
- Energy conservation and creating energy gap
- iNFTnews | 喝茶送虚拟股票?浅析奈雪的茶“发币”
- [nvidia] CUDA_ VISIBLE_ DEVICES
- [node] NVM version management tool
- Concurrent programming - how to interrupt / stop a running thread?
- Unity ugui how to match and transform coordinates between different UI panels or uis
- Matlab在线性代数中的应用(四):相似矩阵及二次型
- The difference between NPM install -g/-save/-save-dev
猜你喜欢
inux摄像头(mipi接口)简要说明
Do you choose pandas or SQL for the top 1 of data analysis in your mind?
ethtool 原理介绍和解决网卡丢包排查思路(附ethtool源码下载)
Ros2 - configuration development environment (V)
睿智的目标检测59——Pytorch Focal loss详解与在YoloV4当中的实现
Ret2xx---- common CTF template proposition in PWN
Marvell 88e1515 PHY loopback mode test
Import CV2 prompt importerror: libgl so. 1: Cannot open shared object file: no such file or directory
U-Boot初始化及工作流程分析
The problem of configuring opencv in qt5.13.2 is solved in detail
随机推荐
【软件测试】05 -- 软件测试的原则
2022年中纪实 -- 一个普通人的经历
Concurrent programming - deadlock troubleshooting and handling
Ethtool principle introduction and troubleshooting ideas for network card packet loss (with ethtool source code download)
Marvell 88e1515 PHY loopback mode test
SD_ CMD_ RECEIVE_ SHIFT_ REGISTER
SD_ CMD_ SEND_ SHIFT_ REGISTER
扫盲-以太网MII接口类型大全-MII、RMII、SMII、GMII、RGMII、SGMII、XGMII、XAUI、RXAUI
Sre core system understanding
[tf1] save and load parameters
Docker installs MySQL and uses Navicat to connect
[OBS] x264 Code: "buffer_size“
Empire help
数学分析_笔记_第8章:重积分
全局变量和静态变量的初始化
mysql设置触发器问题
Logical structure and physical structure
Build a microservice cluster environment locally and learn to deploy automatically
Application of MATLAB in Linear Algebra (4): similar matrix and quadratic form
2022.06.27_每日一题