Moment For Technology

Chapter 2: Implementing a simple Bean container

Posted on Aug. 9, 2023, 4:15 a.m. by Hailey Lopez
Category: The back-end Tag: The back-end spring


Precipitation, share, grow, let yourself and others can gain something! ?

One, foreword

Go to school, the teacher always say: not you ask, but most of the time do not know what to ask!

You will always be in the small Fu Ge's article preface, found some about growth, learning, feeling and when the content of an introduction, in fact, the reason to write such a paving content, mainly in order to let everyone learn the content of the next have a more relaxed opening and excessive.

Just like when we go to school, if the content of a certain subject is not, the teacher will often say, you have not to ask. But for the students themselves, may have not too much, or do not know what they will not, only to see the teacher out of the paper to find themselves what are not. But if let ask, and do not know from where to ask, ask a radish with mud, there are knowledge loopholes everywhere.

So I hope that with some pre-content, you can learn in a slightly common situation, more or less to pave the way for you to a slightly smoother acceptance period. May be certain time also can dozen dozen chicken blood, stimulative stimulative study, always learn knowledge to come to hand is good!

Second, the target

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 hosting objects. You can configure how each of your Bean objects is created. And how they are built and used in relation to each other.

If a Bean object is managed by the Spring container, the Bean object should be disassembled and stored in the Bean definition in a piece-like fashion. This represents an operation that decouples the object and can be more easily managed by Spring, such as handling cyclic dependencies.

When a Bean object is defined and stored, it is assembled by Spring. This process includes Bean initialization, property filling, and so on. Finally, we can use a Bean instantiated object completely.

The goal of our case in this section is to define a simple Spring container for defining, storing, and retrieving Bean objects.

Three, the design

Any concrete implementation of a data structure that can hold data can be called a container. Examples are ArrayList, LinkedList, HashSet, etc., but in the case of Spring Bean containers, we need a data structure that can be used to store and index names, so HashMap is the best choice.

Here is a brief introduction to HashMap. HashMap is a zipper addressing data structure formed based on disturbance function, load factor, red-black tree transformation and other technical content. It can make data more hashed distribution in hash buckets and linked lists and red-black trees formed during collisions. Its data structure will maximize the complexity of the whole data read between O(1) ~O(Logn) ~O(n), of course, there will be more O(n) linked list search data in extreme cases. However, after a 100,000-datum perturbed function addressee verification test, the data was evenly hashed across the hash bucket index, so HashMap is a good fit for the container implementation of Spring beans.

Another simple Spring Bean container implementation, also need Bean definition, registration, acquisition of three basic steps, simplified design is as follows;

  • Definition: BeanDefinition. This is probably one of the most common classes you'll see when looking at Spring source code, such as Singleton, Prototype, BeanClassName, etc. But now our preliminary implementation will be more simple, only define an Object type to store objects.
  • Registration: This process is similar to storing data in a HashMap, except that the HashMap now holds the object information of the defined Bean.
  • Fetch: Finally, fetch the object. The Bean name is key. After the Spring container initializes the Bean, it can be directly fetched.

Next we will follow this design, do a simple Spring Bean container code implementation. The process of coding is usually not that complicated, but knowing the design process is more important!

Four, implementation,

1. Engineering structure

small-spring-step-01└ ─ ─ the SRC ├ ─ ─ the main │ └ ─ ─ Java │ └ ─ ─ cn. Bugstack. Springframework │ ├ ─ ─ BeanDefinition. Java │ └ ─ ─ the BeanFactory. Java └ ─ ─ the test └ ─ ─ Java └ ─ ─ cn. Bugstack. Springframework. Test ├ ─ ─ bean │ └ ─ ─ UserService. Java └ ─ ─ ApiTest. JavaCopy the code

Project source:

Spring Bean container class relationships, as shown in Figure 2-2

The entire implementation of the Spring Bean container is very simple, including only a simple BeanFactory and BeanDefinition, where the class name is the same as in Spring source code, but the current class implementation will be relatively simplified. In the subsequent implementation process to continue to add content.

  1. BeanDefinition, used to define Bean instantiation information, is currently implemented as an Object to hold objects
  2. BeanFactory, which represents a factory for Bean objects, can store Bean definitions into maps and fetch them.

2. Bean definitions


public class BeanDefinition {

    private Object bean;

    public BeanDefinition(Object bean) {
        this.bean = bean;

    public Object getBean(a) {
        returnbean; }}Copy the code
  • In the current Bean definition, only one Object is used to hold the Bean Object. If you are interested, refer to the Spring source code for this class, which has the same name.
  • However, the following implementation will gradually improve the filling of BeanDefinition related attributes, for example: SCOPE_SINGLETON, SCOPE_PROTOTYPE, ROLE_APPLICATION, ROLE_SUPPORT, ROLE_INFRASTRUCTURE, and Bean Class information.

3. The Bean plant


public class BeanFactory {

    private MapString, 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); }}Copy the code
  • In the Bean factory implementation, there is a Bean registration, where the Bean definition information is registered. Also included in this class are operations to get beans.
  • The Current BeanFactory implementation is still a very simplified implementation, but this simplified implementation is also the ultimate manifestation of Bean usage throughout the Spring container, but the implementation only shows the basic core principles. This will continue to grow in size in subsequent complementary implementations.

Five, the test

1. Prepare


public class UserService {

    public void queryUserInfo(a){
        System.out.println("Query user information"); }}Copy the code
  • A UserService object is simply defined to facilitate subsequent Spring container testing.

2. Test cases


public void test_BeanFactory(a){
    1. Initialize the BeanFactory
    BeanFactory beanFactory = new BeanFactory();
    // 2. Register the bean
    BeanDefinition beanDefinition = new BeanDefinition(new UserService());
    beanFactory.registerBeanDefinition("userService", beanDefinition);
    // 3. Get the bean
    UserService userService = (UserService) beanFactory.getBean("userService");
Copy the code
  • In the single test, there are 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 Bean registration, UserService is directly instantiated and passed to BeanDefinition as an input parameter, which we will implement in the Bean factory in future implementations.

3. Test results

Querying user information Process finished with exit code0
Copy the code
  • As you can see from the test results, the current Spring Bean container case is in a slightly embryonic form.

Six, summarized

  • The whole article on the Spring Bean container is already implemented in a prototype, and this part of the code should not confuse anyone, but you can accept it if you try.
  • But for a knowledge learning, writing code is only the last step, often the whole idea, design, scheme, is more important, as long as you know why, so what, so you can have a real understanding.
  • The next section expands on this project, with more classes than we have today. However, in the realization of each article, I will conduct target analysis and scheme design from a requirement perspective, so that we can pay more attention to the study of technical value in addition to learning coding.

Seven, series recommendation

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.