Why learn the framework? What is Spring?

Why learn the framework? What is Spring?

1. Why learn the framework?

  • The learning framework is equivalent to an upgrade from a "small workshop" to a "factory". The small workshop has to do everything by itself, and the factory is a component assembly, which is characterized by high efficiency.
  • Frameworks are easier to use, simpler and more efficient.

The advantages of the framework (SpringBoot VS Servlet)

Using the Spring Boot project demonstration framework has the following advantages over Servlets:

  1. There is no need to configure Tomcat, just click the "Run" button to run the project, and Spring Boot has a built-in web container (can be run directly
    ).
  2. Quickly add external jar packages.
  3. Quickly release the project (you can release it by using java -jar).
  4. Objects are autowired.

Servlet project development

  1. create project

    • create maven project
    • Find the version and reference information corresponding to the servlet in the central warehouse, and add the servlet framework application to pom.xml
    • Click the maven import framework button to create a java source code project directory and configure the routing file web.xml
  2. Write code

    • Create two classes (one corresponding to one url: one to add user url/delete user url), inherit HttpServlet and rewrite the doGet/doPost method
    • Use request to get parameters
    • Business logic
    • Set the type of return / set the encoding format / use resp to return the result
  3. run project

    • Community version idea installs plug-in smartomcat
    • Download and pressurize a tomcat (external tomcat)
    • Configure smartomcat in idea -> running tomcat points to local tomcat
    • run project
  4. post project

    • Maven packaging, uploading the packaged war / jar to the server
    • Install (download and unzip) tomcat on the server
    • Put the war package into webapps
    • Start tomcat and run the project

SpringBoot project development

  1. create project

    • Create a SpringBoot project directly and check Add project dependencies
  2. Write code

    • Use annotations to write add and delete methods
  3. run project

    • Just run the main method directly (built-in tomcat)
  4. post project

    • Maven packaging, uploading the packaged war / jar to the server
    • Use java -jar xxx.jar to run the project directly

Servlet pain point analysis

  1. Adding an external jar is inconvenient and error-prone, such as adding a mismatched external jar version;

  2. It is inconvenient to configure tomcat when running and debugging;

  3. Publishing is inconvenient, and the servlet project must rely on the external tomcat (external web container) to run.

  4. Routing configuration is inconvenient, one access address corresponds to one Servlet class.

The above pain points can all be solved through the JavaEE advanced framework

SpringBoot VS Servlet

Summary of the advantages of SpringBoot compared to Servlet:

  1. Adding external jars is easier and less error-prone (no need to pay attention to version issues);

  2. It is more convenient to debug the project without configuring Tomcat;

  3. Publishing projects is more convenient, no need to configure Tomcat;

  4. Adding routes is more convenient, without adding a class for each access address

How to learn framework

  • Start with the basic framework Spring (toolbox)
  • Spring Boot rapid development of Spring scaffolding
  • MyBatis quick operation database
  • Miscellaneous: logs, transactions, interceptors...

Difficulties in framework learning

  1. There are many configurations.

  2. A large number of external jar packages are required, and it is easy to make mistakes when downloading.

  3. It will involve simple software engineering design ideas (layered thinking: front-end and back-end layered thinking; back-end engineering layered thinking).

  4. The knowledge points are relatively more scattered than the previous knowledge, and you have to listen carefully to understand the logical relationship between each knowledge point.


2. What is Spring?

The Spring we usually refer to refers to the Spring Framework (Spring Framework), which is an open source framework with an active and large community, which is why it can last for a long time. Spring supports a wide range of application scenarios, and it can make Java enterprise-level application development easier.

Summarize Spring in one sentence: Spring is an IoC container that contains many tools and methods

1. Container

A container is a (basic) device used to hold something. ——From: Baidu Encyclopedia

Let's think about it, what kind of containers did we touch in the previous course?

  • List/Map -> data storage container
  • Tomcat -> Web container

2、loC

Spring is also a container. What kind of container is Spring? Spring is an IoC container.

What are IoCs?
IoC = Inversion of Control translated into Chinese means inversion of control, that is to say, Spring is an "inversion of control" container. How to understand this sentence, let's start with the following example

2.1. Traditional program development NewCarExample

Suppose, we build a "car" program now, our implementation idea is as follows:

insert image description here

Build a car (Car Class), but the car needs to rely on the body (FrameWork Class), and the body needs to rely on the chassis (BottomClass), and the chassis needs to rely on the tires (Tire Class). The implementation code of the final program is as follows:

public class NewCarExample {
    
    
    public static void main(String[] args) {
    
    
        Car car = new Car();
        car.init();
    }

    /**
     * 汽⻋对象
     */
    static class Car {
    
    
        public void init() {
    
    
            // 依赖⻋身
            Framework framework = new Framework();
            framework.init();
        }
    }

    /**
     * ⻋身类
     */
    static class Framework {
    
    
        public void init() {
    
    
            // 依赖底盘
            Bottom bottom = new Bottom();
            bottom.init();
        }
    }

    /**
     * 底盘类
     */
    static class Bottom {
    
    
        public void init() {
    
    
            // 依赖轮胎
            Tire tire = new Tire();
            tire.init();
        }
    }

    /**
     * 轮胎类
     */
    static class Tire {
    
    
        // 尺⼨
        private int size = 30;
        
        public void init() {
    
    
            System.out.println("轮胎尺⼨:" + size);
        }
    }
}

Run results: Tire size: 30

If you need to change the requirements, provide a size, customize different tire sizes according to the given size, and modify the code:

	static class Tire {
    
    
        // 尺⼨
        private int size = 30;
        
        public void init(int size) {
    
    
            System.out.println("轮胎尺⼨:" + size);
        }
    }

But not just modifying the tires, because the chassis needs to rely on the tires, the chassis also needs to be changed

insert image description here

Modify chassis code:

    /**
     * 底盘类
     */
    static class Bottom {
    
    
        public void init(int size) {
    
    
            // 依赖轮胎
            Tire tire = new Tire();
            tire.init(size);
        }
    }

Keep modifying up...


2.1.1. Defects of traditional program development NewCarUpdateExample

As can be seen from the above code, the problem with the above program is: when the bottom-level code is changed, all codes in the entire call chain need to be modified

In the above procedure, the size of the tire is fixed. However, as the demand for the right car increases, the individual demand will also increase. At this time, we need to process tires of various sizes. At this time It is necessary to modify the above program

——Solve the defects in traditional development:

We can try not to create lower-level classes in each class. If we create lower-level classes by ourselves, we will have to modify them when the lower-level classes change.
At this point, we only need to change the lower-level class created by ourselves to the way of delivery (that is, the way of injection), because we don't need to create the lower-level class in the current class, so even if the lower-level class changes (creation or reduce parameters), and the current class itself does not need to modify any code, thus completing the decoupling of the program

PS: Decoupling refers to solving the coupling of code, which can also be called program dependency in another way. The coupling (correlation between codes) of good program code is very low, that is, the code should be decoupled

This is like we build a complete car. If all the accessories are made by ourselves, then when the customer's needs change, for example, the size of the tire is no longer the original size, then we We have to change it ourselves, but if we outsource the tires, even if the size of the tires changes, we only need to place an order with the agent factory, and we don’t need it ourselves Forceful

The modified code looks like this:

public class NewCarUpdateExample {
    
    
    public static void main(String[] args) {
    
    
        Tire tire = new Tire(20);
        Bottom bottom = new Bottom(tire);
        Framework framework = new Framework(bottom);
        Car car = new Car(framework);
        car.run();
    }

    static class Car {
    
    
        private Framework framework;
        public Car(Framework framework) {
    
    
            this.framework = framework;
        }
        public void run() {
    
    
            framework.init();
        }
    }

    static class Framework {
    
    
        private Bottom bottom;
        public Framework(Bottom bottom) {
    
    
            this.bottom = bottom;
        }
        public void init() {
    
    
            bottom.init();
        }
    }

    static class Bottom {
    
    
        private Tire tire;
        public Bottom(Tire tire) {
    
    
            this.tire = tire;
        }
        public void init() {
    
    
            tire.init();
        }
    }

    static class Tire {
    
    
        private int size;

        private String color;

        public Tire(int size, String color) {
    
    
            this.size = size;
            this.color = color;
        }
        public void init() {
    
    
            System.out.println("轮胎:" + size);
        }
    }
}

2.2. Inversion of control program development IocCarExample

Based on the above ideas, we modify the program example of calling the car, and change the way of creating subclasses to the way of injecting and passing. The specific implementation code is as follows

public class IocCarExample {
    
    
    public static void main(String[] args) {
    
    
        Tire tire = new Tire(20);
        Bottom bottom = new Bottom(tire);
        Framework framework = new Framework(bottom);
        Car car = new Car(framework);
        car.run();
    }

    static class Car {
    
    
        private Framework framework;
        public Car(Framework framework) {
    
    
            this.framework = framework;
        }
        public void run() {
    
    
            framework.init();
        }
    }

    static class Framework {
    
    
        private Bottom bottom;
        public Framework(Bottom bottom) {
    
    
            this.bottom = bottom;
        }
        public void init() {
    
    
            bottom.init();
        }
    }

    static class Bottom {
    
    
        private Tire tire;
        public Bottom(Tire tire) {
    
    
            this.tire = tire;
        }
        public void init() {
    
    
            tire.init();
        }
    }

    static class Tire {
    
    
        private int size;
        public Tire(int size) {
    
    
            this.size = size;
        }
        public void init() {
    
    
            System.out.println("轮胎:" + size);
        }
    }
}

Change the requirements at this time, add a tire color, and modify the code:

insert image description here

insert image description here

Running result: Tire: 20 - Color: black

After the code is adjusted above, no matter how the underlying class changes, the entire call chain does not need to be changed . This completes the decoupling between the codes , thus realizing a more flexible and general program design


2.3. Comparison and summary rules

The order of object creation in traditional code is: Car -> Framework -> Bottom -> Tire The
object creation order of decoupled code after improvement is: Tire -> Bottom -> Framework -> Car

insert image description here

We found a rule: in the implementation code of the general program, the creation order of the classes is reversed. In the traditional code, the Car controls and creates the Framework, and the Framework creates and creates the Bottom . The inversion of the upper-level object is no longer created and controlled by the upper-level object, but the lower-level object is injected into the current object, and the lower-level control is no longer controlled by the upper-level class, so that even if there is any change in the lower-level class is unaffected, this is a typical inversion of control , which is the realization idea of ​​IoC

**loC advantages: **Realize code decoupling; the object (Bean) life cycle is handed over to the loC framework for maintenance, and programmers do not need to pay attention.


3. Understand Spring IoC

  • Spring is an IoC container that contains multiple tools and methods, which is the core summary of Spring.
  • Since Spring is an IoC (Inversion of Control) container, and the focus is still on the word "container", it has two basic functions:

The core functions of the Spring loC container:

  • Store Bean (object) in Spring (container).

  • Take the Bean (object) out of the Spring (container).

That is to say, the core function of learning Spring is to learn how to store objects in Spring and then get objects from Spring.

**Benefits of storing objects in containers: **Storing objects in IoC containers is equivalent to making all the tools that may be used in the future and putting them in the warehouse. Just take them when you need them, and put them away when you are done using them. Go back to the warehouse. The method of new object is equivalent to that every time a tool is needed, it is made now, and it is thrown away after use and will not be saved. It has to be redone next time it is used again. This is the difference between IoC container and ordinary program development.

Spring is an IoC container, which means that the rights to create and destroy objects are all managed by Spring, and it has the ability to store and retrieve objects


4. DI concept description

When it comes to IoC, one word that has to be mentioned is "DI", DI is Dependency Injectionthe abbreviation of , translated into Chinese means "Dependency Injection"

The so-called dependency injection means that the IoC container dynamically injects certain dependencies into objects during runtime. Therefore, Dependency Injection (DI) and Inversion of Control (IoC) describe the same thing from different perspectives , that is, by introducing an IoC container and using dependency injection to achieve decoupling between objects.

IoC is a "goal" and a kind of thought , and the goal and thought are just a kind of guiding principle . In the end, there must be a feasible landing plan, and DI belongs to the specific realization

For example, I am in a better mood today, and reward myself with a good meal, then "eat a good meal" is the thought and goal (IoC), but in the end, should I eat KF or Yang Guofu? This is the concrete implementation, which is DI


Guess you like

Origin blog.csdn.net/qq_56884023/article/details/131871965