当前位置:网站首页>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();
}
}
边栏推荐
- Ros2 - ros2 vs. ros1 (II)
- 【Node】nvm 版本管理工具
- MySQL setting trigger problem
- Pytorch has been installed in anaconda, and pycharm normally runs code, but vs code displays no module named 'torch‘
- Error: "mountvolume.setup failed for volume PVC fault handling
- ROS2——工作空间(五)
- The difference between new and malloc
- 睿智的目标检测59——Pytorch Focal loss详解与在YoloV4当中的实现
- Negative number storage and type conversion in programs
- SD_CMD_RECEIVE_SHIFT_REGISTER
猜你喜欢
Mipi interface, DVP interface and CSI interface of camera
SD_ CMD_ SEND_ SHIFT_ REGISTER
U-Boot初始化及工作流程分析
C语言数组专题训练
Mathematical analysis_ Notes_ Chapter 8: multiple integral
ROS2——安装ROS2(三)
ethtool 原理介绍和解决网卡丢包排查思路(附ethtool源码下载)
Ros2 - common command line (IV)
[software testing] 04 -- software testing and software development
扫盲-以太网MII接口类型大全-MII、RMII、SMII、GMII、RGMII、SGMII、XGMII、XAUI、RXAUI
随机推荐
Database SQL practice 3. Find the current salary details of the current leaders of each department and their corresponding department number Dept_ no
解读最早的草图-图像翻译工作SketchyGAN
[OBS] x264 Code: "buffer_size“
Now there are HTML files and MVC made with vs (connected to the database). How can they be connected?
Xavier CPU & GPU 高负载功耗测试
The difference between NPM install -g/-save/-save-dev
window navicat连接阿里云服务器mysql步骤及常见问题
Orin two brushing methods
ROS2——功能包(六)
[software testing] 06 -- basic process of software testing
你心目中的数据分析 Top 1 选 Pandas 还是选 SQL?
1290_ Implementation analysis of prvtaskistasksuspended() interface in FreeRTOS
M2dgr slam data set of multi-source and multi scene ground robot
Negative number storage and type conversion in programs
Anaconda navigator click open no response, can not start error prompt attributeerror: 'STR' object has no attribute 'get‘
Ros2 - configuration development environment (V)
Binary search (half search)
Concurrent programming - deadlock troubleshooting and handling
Mathematical analysis_ Notes_ Chapter 8: multiple integral
ROS2——node节点(七)