Creation and use of Spring framework

Table of contents

Spring framework overview

What is the Spring Framework

what is a container

What is an IoC container

Core features of Spring

The difference between IoC container and ordinary program development

FROM

Creation and use of Spring projects

Spring project creation

Create a maven project

Add Spring framework support

Add a startup class

Use of Spring projects

Store Bean objects

Get and use the Bean object

 Operating procedures


Spring framework overview

What is the Spring Framework

The Spring we often say refers to the Spring Framework (Spring Framework), which is an open source framework with an active and huge community. At the same time, Spring also supports a wide range of reference scenarios, which can make Java enterprise-level application development easier.

Generally speaking, Spring is an IoC container that contains many tools and methods.

The above sentence contains two important information, which is also the essence of Spring. So what is a container, and what is an IoC container?

what is a container

Let's think back to what the container we learned before is for.

for example:

  • List/Map is a container for storing data.
  • Tomcat is a container for storing Web sites.

The containers in Spring are actually of the same nature, and they are all used to store things. The specific storage is the object.

What is an IoC container

After we know what is the object stored in the container, what is the IoC container?

IoC: Translated into Chinese means control overturning, that is to say, Spring is a container that controls overturning.

What exactly does the control flip control, and what does it flip?

Object life cycle: In the traditional development process, the life cycle of an object is directly controlled by the programmer. However, in Spring, the life cycle of an object is no longer controlled by the programmer, but is handed over to Spring to manage and control the life cycle of the object. Spring itself has the ability to store objects and retrieve objects. What is controlled is the object, and what is flipped is the control of the object.

The IoC here is a design idea.

Core features of Spring

From the above description, we know that Spring is an IoC container that contains many tools and methods.

Since it is a container, it has two basic functions:

  • store the object in the container
  • get object from container

In other words, the core function of Spring is the process of how to store objects in Spring, and then how to obtain objects from Spring.

The difference between IoC container and ordinary program development

The benefits of storing objects in the IoC container: Storing objects in the IoC container is equivalent to making all the tools that may be used in the future and putting them in the warehouse. Just fetch them when needed, and put them in the warehouse again when they are used up. Ordinary program development is done every time a tool is needed, that is, new. When the new object is used up, it will be thrown away directly and will not be saved. If it is needed next time, it will have to be new. This is the difference between IoC container and ordinary program development.

Another advantage of using the IoC container is that it can achieve decoupling between codes.

FROM

When it comes to IoC, I have to mention DI. DI is the abbreviation of Dependency Injection, which means dependency injection in Chinese.

The so-called dependency injection is to dynamically inject certain dependencies into objects during the running process of the IoC container.

Both Dependency Injection (DI) and Inversion of Control (IoC) describe one thing from different angles. That is, the direct decoupling of objects is achieved by introducing the IoC container and using dependency injection.

IoC is a design idea, while DI is a specific implementation.

Creation and use of Spring projects

We have said so much before, so let's create a Spring project next.


Spring project creation

The Spring project is to create a Spring project through Maven. Creating a Spring project can be divided into 3 steps:

  1. Create a normal maven project
  2. Add Spring framework support (spring-conext, spring-beans)
  3. Add a startup class.

Let's solve it step by step:

Create a maven project

Click Next:

 

Add Spring framework support

In the created project, there is a pom.xml file in which Spring framework support is added, as follows:

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
    </dependencies>

As can be seen from the above added frameworks, the added frameworks include spring-context and spring-beans

spring-context: spring context

spring-beans: a module for spring management objects

From here, we can see that the difference between the spring framework and traditional development is the management of objects (Bean in spring).

Add a startup class

Finally, in the created project, create a startup class in the path of src/main/java, including a main method.

public class App {
    public static void main(String[] args) {
        
    }
}

After the above steps, we have successfully created a spring project. Note that during the above creation process, if there is a red phenomenon in the pom.xml file, then the domestic source of maven is not configured. Regarding the configuration of maven's domestic source, I won't go into details here.

Use of Spring projects

After we have created the spring project, we have to use the spring project.

As I said before, the core functions of spring:

  • Store Bean objects
  • Get the Bean object

Next, the use of spring will also be used around the core functions of these two Springs.

Store Bean objects

Before storing the Bean object, we must first have the Bean object, where the Bean object is an ordinary object.

We first create a Bean object:

 The above directory is created under src/main/java.

The User class is as follows:

package com.dgz.domo;

public class User {
    private int userId;
    private String name;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void sayHi() {
        System.out.println("Hi spring");
    }
    @Override
    public String toString() {
        return "User{" +
                "userId=" + userId +
                ", name='" + name + '\'' +
                '}';
    }
}

So we have a Bean object.

Next we need to store this Bean object in Spring. Before storing, we need to create a Spring configuration file.

Create a spring-config.xml file under the resources folder:

And add the following code in the spring-config.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:content="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
</beans>

 The above code is in a fixed format and does not need to be memorized.

Then we can register the corresponding Bean object in this configuration file.

Next, we register the User object in Spring. The specific operation is to add a bean tag in the beans tag, and then add the properties of the registered User object in it.

    <bean id="user" class="com.dgz.domo.User"></bean>

 Here id is the attribute we need to fill in when we get the Bean object in the future. class is the specific path of the User class.

After the above operations, we will register (store) a Bean object in Spring.

Get and use the Bean object

Obtaining and using the Bean object is divided into 3 steps:

  1. Get the Spring context object, because the objects are all managed by Spring, so you need to get it from Spring, then you need to get the Spring context object.
  2. Obtain a specified Bean object through the Spring context object.
  3. Use the Bean object

Get the Spring context object

Spring context can be obtained by using ApplicationContext.

We can get the context object through the following code in the startup class:


        //得到Spring上下文对象,创建的时候需要配置Spring的配置信息
        ApplicationContext context = new 
ClassPathXmlApplicationContext("spring-config.xml");

In addition to ApplicationContext, we can also use BeanFactory as Spring's context object.

As shown in the following code:

//使用BeanFactory
        BeanFactory factory = new 
XmlBeanFactory( new ClassPathResource("spring-config.xml"));

The difference between these two acquisitions of Spring context objects: (interview questions)

The difference between ApplicationContext and BeanFactory:

  1. ApplicationContext is a subclass of BeanFactory, and ApplicationContext has more functions.
  2. The mechanism of loading beans is different. BeanFactory is lazy loaded and loaded on demand. (Using a bean to load a bean) ApplicationContext loads all bean objects at once.
  3. ApplicationContext starts slowly, but gets objects very quickly after startup. BeanFactory starts fast and takes up little memory, but getting objects later is very slow.

Get the specified Bean object

The following code:

public class App {
    public static void main(String[] args) {

        //得到Spring上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        //使用BeanFactory
        BeanFactory factory = new XmlBeanFactory( new ClassPathResource("spring-config.xml"));

        //使用ApplicationContext的方式来获取Bean对象
        User user = (User) context.getBean("user");
    }
}

Here we need to pay attention to whether we are familiar with the parameters in getBean. This parameter is the id attribute we configured in the spring-config.xml file before.

The ids here need to correspond one by one:

 More usages of getBean:

getBean has many overloaded methods, and we can also obtain Bean objects in other ways, such as the following:

        //根据类型来获取Bean
        User user1 = context.getBean(User.class);

        //根据id+类型来获取Bean
        User user2 = context.getBean("user",User.class);

 The difference between these two methods is that when a class is repeatedly registered in spring-config.xml, it can only be obtained by name

 We register a class repeatedly in spring-config.xml, and then obtain it through the above two methods, and we will find that an error is reported.

The above error means that two user objects have been found, but the acquisition method cannot distinguish which Bean is to be acquired. In this case, the id acquisition method must be used to obtain the id+type method.

Use the Bean object

Since we have obtained the Bean object in various ways before, we can use the Bean object at this time.

public class App {
    public static void main(String[] args) {
        //得到Spring上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        //使用BeanFactory
        BeanFactory factory = new XmlBeanFactory( new ClassPathResource("spring-config.xml"));
        //使用ApplicationContext的方式来获取Bean对象
        //根据id来获取Bean
        User user = (User) context.getBean("user");
        //根据类型来获取Bean
       // User user1 = context.getBean(User.class);
        //根据id+类型来获取Bean
       /* User user2 = context.getBean("user",User.class);
        User user3 = context.getBean("user1",User.class);*/

        //使用Bean对象
        user.sayHi();

    }
}

 Operating procedures

Guess you like

Origin blog.csdn.net/qq_63525426/article/details/131805868