From the creation of Spring to the storage and reading of Bean objects

Table of contents

Create a Spring project:

1. Create a Maven project:

 2. Add Spring framework support:

3. Configure resource files:

4. Add startup class:

Use of Bean objects:

1. Store the Bean object:

1.1 Create Bean:

1.2 Store Bean in the container:

2. Get the Bean object:

2.1 Create a Spring context:

2.2 Get the specified Bean object:

The difference between ApplicationContext and BeanFactory:

ApplicationContext:

BeanFactory:

Summarize:

Three commonly used getBean:

Get by id:

Object type acquisition:

id + object type get:

Summarize



Create a Spring project:

        Creating a Spring project is divided into four steps:

  1.  Create a normal Maven project;
  2.  Add Spring framework support;
  3.  configuration resource file;
  4.  Add startup class;

1. Create a Maven project:

Premise statement: Individuals try to use idea2021 as much as possible, because related plug-ins after version 2022 are charged;

 2. Add Spring framework support:

        Add this configuration dependency to the pom.xml file of the Spring project: Refresh and download to the local warehouse

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.24</version>
        </dependency>
    </dependencies>

3. Configure resource files:

        Create a xxx.xml file in the resources package, and then add the spring configuration file into it:

<?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">
    <content:component-scan base-package="com.spring.demo"></content:component-scan>
</beans>

4. Add startup class:

        Create a class under the java file specifically to start the test:

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

    }
}


Use of Bean objects:

1. Store the Bean object:

        Principle: The Spring framework has spring-context to manage the spring context, and spring-beans to manage object modules;

        What is a Bean object? Objects reused in the project can be regarded as Bean objects, and storing Bean objects means putting the objects required by the project into the Spring container;

1.1 Create Bean:

        Now create an ordinary Student class, which comes with a sayHi() method. Since I will use this class frequently in the future, it can be regarded as a Bean:

public class Student {
    public void sayHi() {
        System.out.println("hi student");
    }
}

1.2 Store Bean in the container:

        The storage bean is also equivalent to the role of "declaration". First, open the spring-config.xml configuration file just created in the resources package:

The format of the storage bean:

<bean id="" class=""><bean>

If the bean is in a multi-level package, pay attention to the path when setting the class attribute;

Now add the Student class as a bean: pay attention to the path

<!--    将Bean对象(com.spring.demo.com.spring.demo.Student)
存到 Spring容器中,它的 id 为 student-->
    <bean id="student" class="com.spring.demo.Student"></bean>

2. Get the Bean object:

        Obtaining the bean object is divided into three steps:

  1. Get the Spring context object: because the Bean object is handed over to Spring for management, you must first get Spring before you have permission to operate the container;
  2. Obtain the Bean object in the container through the Spring context;
  3. Use the Bean object;

2.1 Create a Spring context:

        Here you need to understand two interfaces: ApplicationContext and BeanFactory ;

        grammar:

ApplicationContext context = 
                new ClassPathXmlApplicationContext("spring-config.xml");
 BeanFactory beanFactory =
                new XmlBeanFactory(new ClassPathResource("spring-config.xml"));

2.2 Get the specified Bean object:

        Here it is demonstrated with the help of ApplicationContext:

public class School {
    public static void main(String[] args) {
        // 1.得到 Spring 上下文
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        // 2.获取指定 Bean 对象
        Student student = (Student) context.getBean("student");
        // 3.使用 Bean 对象
        student.sayHi();
    }
}

So far, the creation of Spring, the storage and acquisition of beans have been basically introduced;


The difference between ApplicationContext and BeanFactory:

        In the above code, add another Teacher class as a new Bean and add it to the container:

public class Teacher {
    public Teacher() {
        System.out.println("do teacher init");
    }

    public void sayHi() {
        System.out.println("hi teacher");
    }
}
    <bean id="student" class="com.spring.demo.Student"></bean>
    <bean id="teacher" class="com.spring.demo.Teacher"></bean>

At this point, there are two beans in our container: one is Student and the other is Teacher;

        Use ApplicationContext and BeanFactory to operate respectively: both only try to get the Student Bean in the container to see the difference in their effects.

ApplicationContext:

        The original code remains unchanged: 

public class School {
    public static void main(String[] args) {
        // 1.得到 Spring 上下文
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        // 2.获取指定 Bean 对象
        Student student = (Student) context.getBean("student");
        // 3.使用 Bean 对象
        student.sayHi();
    }
}

BeanFactory:

        Create a new startup class: School2, get the Spring context and ApplicationContext is not the same, the other does not need to change.

public class School2 {
    public static void main(String[] args) {
        // 1.使用 BeanFactory 来获取 Spring 上下文 
        BeanFactory beanFactory =
                new XmlBeanFactory(new ClassPathResource("spring-config.xml"));
        // 2. 从 Spring 容器中获取 bean 对象
        Student student = (Student) beanFactory.getBean("student");
        student.sayHi();
    }
}

         Comparing the running results, it is obvious that both of them obtain and use the Bean object with the id "student" at the same time, but the ApplicationContext also takes out the Teacher for the context, and the BeanFactory only gets the Student;

Summarize:

Same point:

  • Both ApplicationContext and BeanFactory obtain the Bean object in the container;

difference:

  •  ApplicationContext loads and initializes all Bean objects in the container at one time (hungry man mode), and BeanFactory loads which one is needed (lazy man mode);
  • ApplicationContext is actually a subclass of BeanFactory. The subclass not only inherits all the functions of the parent class, but also has its own unique functions; and ClassPathXmlApplicationContext belongs to the subclass of ApplicationContext;
  • BeanFactory was also the first to be designed. At the beginning of the design, due to the high cost of machine hardware, only the required objects were loaded; while ApplicationContext was designed later. In order to improve efficiency as much as possible, people thought of loading all Bean objects at once;


Three commonly used getBean:

        The getBean() method has many overloads, compare the following three commonly used ones:

  1. Get according to id;
  2. object type acquisition;
  3. id, object type acquisition;

Get by id:

    <bean id="student" class="com.spring.demo.Student"></bean>
    <bean id="teacher" class="com.spring.demo.Teacher"></bean>
        // 2.获取指定 Bean 对象
        Student student = (Student) context.getBean("student");
        Teacher teacher = (Teacher) context.getBean("teacher");

This method is obviously rude and undesirable, and there is a forced transfer; in addition, if the object obtained through the id is null, an exception will also occur;

Object type acquisition:

    <bean id="student" class="com.spring.demo.Student"></bean>
    <bean id="teacher" class="com.spring.demo.Teacher"></bean>
        // 2.获取指定 Bean 对象
        Student student = context.getBean(Student.class);
        Teacher teacher = context.getBean(Teacher.class);

Although this method is not rude, there is a problem:

        When the same type of Bean is registered twice in the container, the compiler will report NoUniqueBeanDefinitionException;

id + object type get:

        This method is more secure;

    <bean id="student" class="com.spring.demo.Student"></bean>
    <bean id="student2" class="com.spring.demo.Student"></bean>

    <bean id="teacher" class="com.spring.demo.Teacher"></bean>
        // 2.获取指定 Bean 对象
        Student student = context.getBean("student2",Student.class);
        Teacher teacher = context.getBean("teacher",Teacher.class);

Thinking:
         Since it was mentioned that the same type may be registered multiple times in the container, although they only have different ids, do they point to the same space?

        Code verification:

    <bean id="student" class="com.spring.demo.Student"></bean>
    <bean id="student2" class="com.spring.demo.Student"></bean>

    <bean id="teacher" class="com.spring.demo.Teacher"></bean>
public class School {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
       
        Student student1 = context.getBean("student", Student.class);
        Student student2 = context.getBean("student2", Student.class);
       
        System.out.println(student1 == student2);
        System.out.println(student1.equals(student2));
    }
}

Then prove that they are references to different objects;


Summarize:

The creation of Spring project and the basic usage process of Bean:

Guess you like

Origin blog.csdn.net/m0_65190367/article/details/130658114