【Spring】Core and Design Ideas

 Hello, hello, everyone~ I am your old friend: protect Xiao Zhou ღ  


Speaking of frameworks in the Java circle, the oldest and most dazzling one is the Spring framework, which has become one of the most popular and widely used Java development frameworks. I don't know if you have thought about these issues when using the Spring framework. What is a framework? What is Spring? How to understand Spring? What is loC and DI, and what is the difference? What is the core function of Spring? This article will explain it to everyone, let’s take a look~


This issue is included in the blogger's column : JavaEE_Protect Xiao Zhouღ's Blog-CSDN Blog

Suitable for programming beginners, interested friends can subscribe to view other "JavaEE Basics".

Stay tuned for more highlights: Protect Xiaozhou ღ *★,°*:.☆( ̄▽ ̄)/$:*.°★*'


1. What is Spring?

Spring is an open source Java framework with an active and large community (for example: Apache). Spring provides a series of tools and libraries that can help developers build efficient, reliable, and easy-to-maintain enterprise-level applications. Spring's core modules include IOC container , AOP, ORM, etc. It also provides many extension modules such as Spring MVC, Spring Security, Spring Data, etc., which can meet the needs of different scenarios. Originally created in 2002 by Rod Johnson, Spring has become one of the most popular and widely used Java development frameworks today.

Summarize Spring in one sentence: an loC container that contains many tools and methods.

A framework is a software architecture, a collection of codes and class libraries that implement a certain logic or function. We need to use it according to the rules of the framework designer, so in the framework world: "Convention is greater than configuration "

"Convention over Configuration" is a software development philosophy that simplifies the process of configuration and coding by using some agreed-upon default settings and behaviors. Under this concept, the framework automatically completes some tedious configurations according to the pre-declared conventions, continues some default settings and naming rules, so that developers can build applications faster and easier. This can reduce redundant code and duplication of effort, helping developers to better focus on the functional development of the application.

To give an inappropriate example : just like the library functions we use, we don’t need to pay attention to the implementation of the library functions. What we care about is the application scenarios of these library functions, what functions they have, how we use them, and what are the parameters. The parameters and usage of the function can be considered as an agreement between the function and the developer~

1.1 What is an loC container

"Container": A "ware" that can store something is called a container, such as a water cup.

The concept of containers has actually been touched in the JavaSE (grammar) stage. Our collection classes, ArrayLIst, Map, and Set are all containers, which are containers for receiving data.

loC (In) Inversion of Control translated into Chinese means "inversion of control". Inversion of control is a kind of programming design idea , which changes the control flow of the program from the traditional active calling method to the passive receiving method, so as to realize the inversion of control between modules. Decoupling and dependency management.

1.1.1 Traditional development model

Suppose, we build a house from the perspective of code, design ideas:

 Build a house (House Class), but the house needs to rely on the house structure (BuildingFame Class), and the house structure needs to rely on the building materials (BuildingMaterials Class), and the building materials need to rely on the foundation (FoundationClass). The implementation code of the final program is as follows:

//这是一个房子类
public class House {
    //一个房子需要依赖房屋的架构
    House() {
        System.out.println("这是一个房子");
    }

    BuildingFame buildingFame = null;
    public void init() {
        //依赖于房屋架构
        System.out.println("执行了初始化房屋架构的方法");
        this.buildingFame = new BuildingFame();
        buildingFame.init();
    }
}

//房屋构架
class BuildingFame {
    //房屋的架构依赖与建筑材料
    BuildingMaterials buildingMaterials = null;
    public void init() {
        //依赖于建筑材料
        System.out.println("执行了初始化建筑材料的方法");
        this.buildingMaterials = new BuildingMaterials();
        buildingMaterials.init();
    }
}

//建筑材料
class BuildingMaterials {
    //建筑材料依赖于地基
    Foundation foundation = null;
    public void init() {
        //依赖于地基
        System.out.println("执行了初始化地基的方法");
        this.foundation = new Foundation();
        foundation.init();
    }
}

//地基
class Foundation {
    public void init() {
        String size = "100m*m";
        //依赖于地基
        System.out.println("地基:" + size);
    }
}

Execution result
:

Disadvantages of traditional development:

In the above procedure, the size (square) of the house foundation is fixed. As the demand for houses increases, the individual needs will also increase. A large family may need a house of 200 square meters , for newly married couples, a house of 100 square meters may be enough. At this time, we have dealt with the size of the house foundation, and also need to modify the above program. The modified code is as follows:

//这是一个房子类
public class House {
    //一个房子需要依赖房屋的架构
    House() {
        System.out.println("这是一个房子");
    }

    BuildingFame buildingFame = null;
    public void init(String size) {
        //依赖于房屋架构
        System.out.println("执行了初始化房屋架构的方法");
        this.buildingFame = new BuildingFame();
        buildingFame.init(size);
    }
}

//房屋构架
class BuildingFame {
    //房屋的架构依赖与建筑材料
    BuildingMaterials buildingMaterials = null;
    public void init(String size) {
        //依赖于建筑材料
        System.out.println("执行了初始化建筑材料的方法");
        this.buildingMaterials = new BuildingMaterials();
        buildingMaterials.init(size);
    }
}

//建筑材料
class BuildingMaterials {
    //建筑材料依赖于地基
    Foundation foundation = null;
    public void init(String size) {
        //依赖于地基
        System.out.println("执行了初始化地基的方法");
        this.foundation = new Foundation();
        foundation.init(size);
    }
}

//地基
class Foundation {
    String size = "100 m*m";
    public void init(String size) {
        this.size = size;
        //依赖于地基
        System.out.println("地基:" + size);
    }
}

The problem that can be seen from the appeal code is: when the bottom-level code needs to be changed, all dependent classes in the entire House class call chain need to be modified, and the dependencies between classes are extremely high.

There are certain defects in the above program design, how can we solve it?


1.1.2 loC inversion of control program development

We can try not to create lower-level classes in each class. If the created class appears to be modified when the lower-level class changes, we have to modify it accordingly. At this time, we only need to change the originally created lower-level class to the way of passing parameters (that is, the way of injection), because we don’t need to create lower-level classes in the current class, and the current class just describes what I need. What kind of class, so even if the subordinate class changes (create or reduce parameters), the current class itself does not need to modify any code, thus completing the decoupling of the program.

Speaking of this, I have to mention what is "decoupling"

High cohesion and low coupling (high cohesion and low coupling) is a software design idea that can effectively improve the maintainability and flexibility of software.

High cohesion: Refers to the fact that the elements inside a module are closely related to each other to complete a specific and clear task without too much interaction with other external elements.

Low coupling: It means that the interdependence between modules is as low as possible, and the modules only interact when they complete some pure tasks, so as to reduce mutual influence and improve the flexibility and scalability of the software.

Using the principle of high cohesion and low coupling can make the software system more flexible and easy to maintain. High cohesion can make the logic inside the module clearer, and each module has specific responsibilities, which is easy to understand and maintain; low coupling can reduce the interdependence between modules, and reduce the need for other modules when modification or refactoring is required. The impact of modules improves the maintainability and scalability of the software.

Based on the above ideas, we modify the program example of building a house, and change the way of creating subclasses to the way of injecting and passing (passing parameters) . The specific implementation code is as follows:

//这是一个房子类
public class House {
    BuildingFame buildingFame = null;
    //一个房子需要依赖房屋的架构
    public House(BuildingFame buildingFame) {
        this.buildingFame = buildingFame;
        System.out.println("这是一个房子");
    }

    public void init() {
        //依赖于房屋架构
        System.out.println("执行了初始化房屋架构的方法");
        buildingFame.init();
    }
}

//房屋构架
class BuildingFame {
    //房屋的架构依赖与建筑材料
    BuildingMaterials buildingMaterials = null;
    public BuildingFame(BuildingMaterials buildingMaterials) {
        this.buildingMaterials = buildingMaterials;
    }

    public void init() {
        //依赖于建筑材料
        System.out.println("执行了初始化建筑材料的方法");
        buildingMaterials.init();
    }
}

//建筑材料
class BuildingMaterials {
    //建筑材料依赖于地基
    Foundation foundation = null;
    public BuildingMaterials(Foundation foundation) {
        this.foundation = foundation;
    }

    public void init() {
        //依赖于地基
        System.out.println("执行了初始化地基的方法");
        foundation.init();
    }
}

//地基
class Foundation {
    String size = "100 m*m";
    public Foundation(String size) {
        this.size = size;
    }

    public void init() {
        //依赖于地基
        System.out.println("地基:" + size);
    }
}

After using the loC control inversion idea, no matter how the dependent class changes, the impact on the entire call chain is minimal, thus completing the decoupling between codes and improving the flexibility and scalability of the program.


summary:

Through the above two examples, we can find that the order of the creation of the two instance classes is reversed. The traditional code House controls and creates BuildingFame, and BuildingFame creates BuildingMaterials... Created in turn, after using loC control inversion, It is no longer the upper-level object to create and control the lower-level object, but to inject the lower-level object into the current object, so that any changes in the lower-level class will not have any impact on the current class. This is the realization idea of ​​loC.


1.2 Spring is an loC container 

As mentioned above, Spring is summarized in one sentence : an loC container that contains multiple tool methods . The blogger also explained to you what is the idea of ​​loC (inversion of control) through examples.

The focus is still on the "container". Since it is a container, it has two basic functions:

  • store the object in the container;
  • remove the object from the container;

This is also the core function of the Spring framework, which is the process of learning how to store objects in Spring and how to get objects from Spring.

The advantage of putting the created object in the container: the object is stored in the loC container, just like putting the tool in the toolbox, just take it directly from the tool when needed, and put it back into the toolbox after using the tool Among them, the new object method is like, every time you need to use a tool, you find that you don’t have one, you can only “buy one” on the spot, and you don’t save it after you use it up. You have to “buy” it when you need it next time. This is The essential difference between loC container and ordinary program development.

How to store objects in Spring and how to get objects from Spring will be the core of the next issue, please look forward to it.


1.3 The concept of DI

When it comes to loC design ideas, you have to mention "DI" ( abbreviation for Dependency Injection - "Dependency Injection" )

" Dependency injection " refers to the dynamic injection of certain dependencies into objects by the IoC container during runtime (during program execution). The traditional approach is for the program to actively find and instantiate the objects it depends on, while DI is for the container to actively inject dependencies into the objects. The advantage of this is that objects are decoupled, which improves code reusability and maintainability. Through DI, the life cycle of objects can be uniformly controlled, reducing the waste of resources.

From a broad perspective, loC and DI describe the same thing, but from different perspectives, loC is a design idea (inversion of control) and a guiding principle, while DI is the concrete realization of the idea of ​​loC——IoC container is running (During program execution), dynamically inject certain dependencies into objects.

Objects stored in Spring are also called "Bean objects".

Example: I need a house,

loC: I think to build a house, you need to build a foundation first, then buy building materials, then build the whole house structure, and do the decoration slowly, so this is a kind of design idea and purpose of building a house.

DI : Hey, Boss Zhang, I want to build a house. You send an excavator to help me dig the foundation. Hey, Boss Li, I want to build a house. Help me bring some sand, stone, and reinforced concrete... , Hey Hey, Boss Wang, it’s like this. I want to build a house. You can arrange workers to help me build the house. The foundation and building materials are already in place, and the price is negotiable. DI is the specific implementation of the guiding ideology.


Well, here we are, bloggers of  [Spring] core and design ideas  have finished sharing, I hope it will be helpful to everyone, and welcome criticism and correction if there is anything wrong.

Thank you to everyone who read this article, and more exciting events are coming: Protect Xiaozhou ღ *★,°*:.☆( ̄▽ ̄)/$:*.°★* 

When I met you, all the stars fell on my head ...

Guess you like

Origin blog.csdn.net/weixin_67603503/article/details/131113710