[JavaEE Advanced] Spring creation and use

insert image description here

Spring creation and use


1, the creation of the Spring project

Use the Maven method to create a Spring project. Creating a Spring project is similar to Servlet. It is divided into the following 3 steps:

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

1.1, create a Maven project

Points to note when creating an ordinary Maven project: there cannot be any Chinese in the project name and project path.

image-20230707094943941

When the color of the Java source code root directory and the logo image of the resources resource directory appear, it means that the Maven project has been initialized.

image-20230707095538477

1.2, add Spring framework dependency

spring-contextAdd the Spring framework dependency ( dependency) in the pom.xml of the project , and the xml configuration is as follows:

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

After adding dependencies in the pom.xml configuration file of the project spring-context, you need to click the refresh button to reload the Maven project. The operation is as follows:

image-20230707100320326

When External Librathe following 6 libraries appear in the directory, it indicates that Spring-contextthe dependency is added successfully.

image-20230707100551575

Question: I only added one Spring-contextdependency in pom.xml, but why are there 6 dependencies in the end?

Answer: Spring-contextThe underlying implementation of the dependency depends on the other five framework dependencies, so when adding Spring-contextdependencies, the other five will also be added.

1.3, add startup class

Create a startup class under the root directory java of the Java source code, and the startup class only needs to contain the main method.

The function of the startup class is to prepare for reading beans from the Spring container later.

image-20230707101025123

To test whether the Maven project is successfully created, you can write test code in the main method, and judge according to whether the code can run successfully.

image-20230707101614936

Note: The above test code can run normally, indicating that the Maven project is created and configured successfully.


2. Storage Bean

2.1, create a Bean object

The Bean object is an ordinary object in the Java language, but the object can be called and used multiple times.

image-20230707102220350

2.2, register the bean with Spring

Operation process: Add a Spring configuration file under the resources resource directory spring-config.xml, and add the following configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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>

Add a schematic diagram of a configuration file under the resources resource directory:

image-20230707103329843

After adding the configuration file, you can register the Bean object in Spring. The specific operation is to add the following configuration in:

image-20230707103611886

Note: idIndicate the name of the Bean object and classthe path of the Bean object (package name + class name).

<bean id="student" class="org.example.Student"></bean>

The meaning of the above representation is: store the Bean (org.example.Student) in the Spring container, and its name is called student.


3. Read Bean

3.1, get the Spring context

The acquisition of the Spring context object can be used ApplicationContex, and the Spring configuration information needs to be configured when creating it.

ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

Description: ClassPathXmlApplicationContextIt belongs to ApplicationContextthe subclass and has ApplicationContextall the functions. It is to obtain all the Bean objects in the Spring container through the xml configuration.

image-20230707104530977

Note: ClassPathXmlApplicationContextThe parameter value in configLocationshould be the same as the Spring configuration information file name.

3.2, get the specified Bean object

idRequirements for obtaining the specified Bean object: the sum of the parameter value of getBean should correspond to the sum classof the specified Bean object .idclass

Student student = context.getBean("student", Student.class);

Obtain the schematic diagram of the specified Bean object:

image-20230707110153870

3.3, using the Bean object

student.sayHi();

The total operation process code for reading the Bean object and using it:

import org.example.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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

The total operation process code execution result of reading and using the Bean object:

image-20230707110725900


4. Other attention issues

4.1, two ways to get the Spring context

1)ApplicationContext

ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

ApplicationContextExecute the operation code:

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

Execute ApplicationContextthe print result:

image-20230707112101914

2)BeanFactory

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

BeanFactoryExecute the operation code:

public static void main(String[] args) {
    
    
    //1,获得Spring对象上下文
    BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("spring-config.xml"));
    //2,获取指定的Bean对象
    Student student = beanFactory.getBean("student", Student.class);
    //3,使用Bean对象(非必须)
    student.sayHi();
}

Execute BeanFactorytthe print result:

image-20230707112157734

3) The difference between the two methods

1. Prepare the Student class (Bean object)

public class Student {
    
    
    public Student(){
    
    
        System.out.println("do student init!");
    }

    public void sayHi(){
    
    
        System.out.println("Hi student!");
    }
}

2, Teacher class (Bean object) preparation

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

    public void sayHi(){
    
    
        System.out.println("Hi teacher!");
    }
}

3. Comparison of two methods

Execute ApplicationContext(without obtaining the specified Bean object operation) and print the result:

image-20230707113429506

Execute BeanFactoryt(with the operation of obtaining the specified Bean object) and print the result:

image-20230707113921760

Execute BeanFactoryt(with the operation of obtaining the specified Bean object) and print the result:

image-20230707114511703

4. Summary of the difference between the two methods

ApplicationContext : This method loads and initializes all Bean objects in the Spring container when obtaining the Spring object context.

Method features : relatively memory-consuming, one-time loading, subsequent reading of Bean objects does not need to be loaded and initialized, and the efficiency is high.

BeanFactory : This method only loads and initializes the corresponding Bean object when the getBean method is called, not all Bean objects, which belongs to lazy loading.

Method features : save memory, lazy loading, only when getBean is called, the corresponding Bean object will be loaded and initialized, which is not efficient.

ApplicationContextand BeanFactorythe link:

ApplicationContextBoth BeanFactoryare interfaces, and their subclasses are called when they are used.

image-20230707185048579

Comparison and difference between the two methods: compare and explain from the two aspects of inheritance function and performance.

  1. Inheritance relationship and functions : BeanFactory provides the basic ability to access containers, and ApplicationContext is a subclass of BeanFactory. In addition to inheriting all the functions of BeanFactory, it also has unique features and adds support for internationalization and resources. Access support, and event propagation support.
  2. In terms of performance : ApplicationContext loads and initializes all Bean objects at one time, and BeanFactory needs to load and initialize which one, so BeanFactory is lighter, but not efficient.

4.2, three ways to obtain Bean objects

1) Get by name

Student student = (Student) context.getBean("student");

This method needs to go through two steps, first obtain the Bean object, and then convert it to the corresponding type through forced type conversion, but the forced type conversion is prone to null pointer exceptions, which is not elegant.

If the Bean object name does not exist, NoSuchBeanDefinitionExceptionan exception will be thrown.

image-20230707115428718

2) Obtain by class name

Student student = context.getBean(Student.class);

NoUniqueBeanDefinitionExceptionThere are defects in this method. When a type is repeatedly registered in spring-config.xml, this method cannot be used. If used, an exception (non-unique Bean exception) will be thrown .

image-20230707123153944

3) Obtain by name + class name

This method is recommended. It not only avoids the null pointer exception problem caused by forced type conversion, but also avoids the non-unique Bean exception problem caused by only obtaining the bean based on the class name.

Student student = context.getBean("student", Student.class);

Summary of this article

1. What is the process of creating and using Spring?

Answer: The process of creating and using Spring is divided into three steps, which are the creation of Spring projects, the storage of Bean objects, and the reading of Bean objects. The specific process is:

1) Creation of Spring project

  1. Create a Maven project
  2. Add Spring framework dependency [spring-context]
  3. Add startup class [Function: Prepare for reading Bean from Spring container later]

2) Storage Bean

  1. Create a Bean object
  2. Register the Bean in the Spring container [spring-config.xml configuration file]

3) Read the Bean

  1. Get the Spring object [ApplicationContext, BeanFactory]
  2. Obtain the Bean object through the getBean() method of the Spring object [DI operation]
  3. Use Bean object [not required]

Schematic diagram of the process of creating and using Spring:


2. Two ways to get Spring? the difference?

1) ApplicationContext : When obtaining the Spring object context, all Bean objects in the Spring container will be loaded and initialized.

ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

2) BeanFactory : Only when the getBean method is called will the corresponding Bean object be loaded and initialized, not all Bean objects.

BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("spring-config.xml"))

3) The difference between the two methods : compare and explain from the aspects of inheritance function and performance.

  1. Inheritance relationship and functions : BeanFactory provides the basic ability to access containers, and ApplicationContext is a subclass of BeanFactory. In addition to inheriting all the functions of BeanFactory, it also has unique features and adds support for internationalization and resources. Access support, and event propagation support.
  2. In terms of performance : ApplicationContext loads and initializes all Bean objects at one time, and BeanFactory needs to load and initialize which one, so BeanFactory is lighter, but not efficient.

3. Three ways to obtain Bean objects?

1) Get by name : flawed, requires a cast, and casts are prone to null pointer exceptions.

Student student = (Student) context.getBean("student");

2) Obtaining by class name : defective, when there are multiple Bean objects of the same type, NoUniqueBeanDefinitionExceptionan exception is thrown (non-unique Bean exception).

Student student = context.getBean(Student.class);

3) Obtain by name + class name : recommended to avoid the above problems.

Student student = context.getBean("student", Student.class);

Guess you like

Origin blog.csdn.net/m0_64338546/article/details/131620968