Author: Xiao Fu Ge
Blog: https://bugstack.cn
Precipitate, share, and grow, so that you and others can gain something! 😄
I. Introduction
school, my teacher always said: "If you don't know, just ask, but most of the time I don't know what to ask!"
You will always find in the preface of Xiao Fu's article about growth, learning, feelings, and an introduction to the content of the article. In fact, the reason why you write such a foreshadowing content is mainly to let everyone learn about the next content. A more relaxed opening and transition.
Just like when we were in school, if the content of a certain subject was not good, the teacher would often say that you should ask if you don’t. But for the students themselves, they may not know too much, or they do not know what they do. Only when they see the test papers that the teacher has finished, they realize that they do not know anything. But if you ask, but don't know where to ask, if you ask the carrots to bring out the mud, there will be knowledge loopholes everywhere.
So I hope to use some pre-contents to pave the way, so that everyone can learn in a scene with a little consensus, and more or less pave the way for you to have a gentle acceptance period. It is possible that at some point, it will be smashing, stimulating and stimulating learning, and it is always good to learn the knowledge!
2. Goal
What is the Spring Bean container?
Spring contains and manages the configuration and life cycle of application objects. In this sense, it is a container for carrying objects. You can configure how each of your Bean objects is created, and these Beans can create a separate instance Or generate a new instance every time you need it, and how they are built and used in relation to each other.
If a Bean object is handed over to the Spring container for management, then the Bean object should be disassembled in a similar way and stored in the Bean definition, which is equivalent to an operation of decoupling objects, which can be made easier by Spring Management is like handling circular dependencies and other operations.
After a Bean object is defined and stored, it is assembled by Spring. This process includes Bean initialization, attribute filling, etc. Finally, we can use a Bean instantiated object completely.
The goal of our case in this chapter is to define a simple Spring container for defining, storing and obtaining Bean objects.
Three, design
Any implementation of a specific data structure that can store data can be called a container. For example: ArrayList, LinkedList, HashSet, etc., but in the context of the Spring Bean container, we need a data structure that can be used for storage and name indexing, so choosing HashMap is the most appropriate.
Here is a brief introduction to HashMap. HashMap is a zipper addressing data structure based on technical content such as disturbance function, load factor, red-black tree conversion, etc. It can make data more hashed and distributed in hash buckets and collisions. Form the linked list and the red-black tree. Its data structure will maximize the complexity of reading the entire data between O(1) ~ O(Logn) ~ O(n). Of course, there will be O(n) linked list lookups in extreme cases. The situation with more data. However, after we pass the perturbation function of 100,000 data and then address the verification test, the data will be evenly hashed on each hash bucket index, so HashMap is very suitable for use in the container implementation of Spring Bean.
Another simple implementation of Spring Bean container requires three basic steps of Bean definition, registration, and acquisition. The simplified design is as follows:
- Definition: BeanDefinition, maybe this is a class you often see when you look up Spring source code, for example, it will include singleton, prototype, BeanClassName, etc. But at present, our preliminary implementation will make it easier to deal with, and only define an Object type for storing objects.
- Registration: This process is equivalent to storing the data in the HashMap, but now the HashMap stores the object information of the defined Bean.
- Obtain: Finally, the object is obtained. The name of the Bean is the key. After the Spring container initializes the Bean, it can be obtained directly.
Next, we follow this design and make a simple Spring Bean container code implementation. coding process is often not that complicated, but knowing the design process is even more important!
Fourth, realize
1. Engineering structure
small-spring-step-01
└── src
├── main
│ └── java
│ └── cn.bugstack.springframework
│ ├── BeanDefinition.java
│ └── BeanFactory.java
└── test
└── java
└── cn.bugstack.springframework.test
├── bean
│ └── UserService.java
└── ApiTest.java
Engineering source code: https://github.com/small-spring/small-spring-step-01
Spring Bean container class relationship, as shown in Figure 2-2
The entire implementation of the Spring Bean container is very simple, and it only includes a simple BeanFactory and BeanDefinition. The class name here is consistent with the Spring source code, but the current class implementation will be relatively simplified. In the follow-up Continue to add content during the implementation process.
- BeanDefinition, used to define Bean instantiation information, the current implementation is to store the object in an Object
- BeanFactory represents a factory of Bean objects, which can store Bean definitions in Map and obtain them.
2. Bean definition
cn.bugstack.springframework.BeanDefinition
public class BeanDefinition {
private Object bean;
public BeanDefinition(Object bean) {
this.bean = bean;
}
public Object getBean() {
return bean;
}
}
- In the current Bean definition, only one Object is used to store the Bean object. If you are interested, you can refer to the information of this class in the Spring source code, the name is the same.
- However, in subsequent implementations, the filling of BeanDefinition related properties will be gradually improved, such as: SCOPE_SINGLETON, SCOPE_PROTOTYPE, ROLE_APPLICATION, ROLE_SUPPORT, ROLE_INFRASTRUCTURE and Bean Class information.
3. Bean Factory
cn.bugstack.springframework.BeanFactory
public class BeanFactory {
private Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
public Object getBean(String name) {
return beanDefinitionMap.get(name).getBean();
}
public void registerBeanDefinition(String name, BeanDefinition beanDefinition) {
beanDefinitionMap.put(name, beanDefinition);
}
}
- In the implementation of the Bean factory, the registration of the Bean is included, and the definition information of the Bean is registered here. At the same time, the operation of obtaining Bean is also included in this class.
- The current BeanFactory is still a very simplified implementation, but this simplified implementation is also the final manifestation of the use of Beans in the entire Spring container, but the implementation process only shows the basic core principles. In subsequent supplementary implementations, this will continue to become huge.
Five, test
1. Prepare in advance
cn.bugstack.springframework.test.bean.UserService
public class UserService {
public void queryUserInfo(){
System.out.println("查询用户信息");
}
}
- Here is a simple definition of a UserService object to facilitate our subsequent testing of the Spring container.
2. Test cases
cn.bugstack.springframework.test.ApiTest
@Test
public void test_BeanFactory(){
// 1.初始化 BeanFactory
BeanFactory beanFactory = new BeanFactory();
// 2.注册 bean
BeanDefinition beanDefinition = new BeanDefinition(new UserService());
beanFactory.registerBeanDefinition("userService", beanDefinition);
// 3.获取 bean
UserService userService = (UserService) beanFactory.getBean("userService");
userService.queryUserInfo();
}
- In the single test, it mainly includes three steps: initializing the Bean factory, registering the Bean, and obtaining the Bean. The use effect is close to Spring, but it will be more simplified.
- In the registration of Bean, the UserService is directly instantiated and passed to the BeanDefinition as an input parameter. In subsequent implementations, we will put this part of the content into the Bean factory.
3. Test results
查询用户信息
Process finished with exit code 0
- Through the test results, we can see that the current Spring Bean container case has already taken shape.
Six, summary
- A prototype of the entire Spring Bean container has been implemented. Relatively speaking, this part of the code will not be difficult for anyone, as long as you try a little, you can accept the implementation of this part of the content.
- But for the learning of knowledge, writing code is only the last step. Often the whole idea, design, and plan are more important. As long as you know what and why, then you can have a true understanding.
- The next chapter will implement expansion based on this project, which is more than the current class. However, in the realization of each article, I will conduct target analysis and program design from a demand perspective, so that everyone can pay more attention to learning more technical value in addition to learning coding.
Seven, series recommendation
- 160a5d0c617977 wrote 200,000 lines of code before graduating, which made me become a face
- HashMap core knowledge, disturbance function, load factor, expansion linked list split, deep learning
- HashMap data insertion, search, deletion, traversal, source code analysis
- Look at the picture and talk, explain the 2-3 balanced tree "the predecessor of the red-black tree"
- "SpringBoot Middleware Design and Development"| Yes, Xiao Fu will teach you how to build a rocket this time!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。