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:
- Create a normal Maven project
- Add Spring framework support (spring-context, spring-beans)
- 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.
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.
1.2, add Spring framework dependency
spring-context
Add 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:
When External Libra
the following 6 libraries appear in the directory, it indicates that Spring-context
the dependency is added successfully.
Question: I only added one Spring-context
dependency in pom.xml, but why are there 6 dependencies in the end?
Answer: Spring-context
The underlying implementation of the dependency depends on the other five framework dependencies, so when adding Spring-context
dependencies, 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.
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.
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.
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:
After adding the configuration file, you can register the Bean object in Spring. The specific operation is to add the following configuration in:
Note: id
Indicate the name of the Bean object and class
the 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: ClassPathXmlApplicationContext
It belongs to ApplicationContext
the subclass and has ApplicationContext
all the functions. It is to obtain all the Bean objects in the Spring container through the xml configuration.
Note: ClassPathXmlApplicationContext
The parameter value in configLocation
should be the same as the Spring configuration information file name.
3.2, get the specified Bean object
id
Requirements for obtaining the specified Bean object: the sum of the parameter value of getBean should correspond to the sum class
of the specified Bean object .id
class
Student student = context.getBean("student", Student.class);
Obtain the schematic diagram of the specified Bean object:
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:
4. Other attention issues
4.1, two ways to get the Spring context
1)ApplicationContext
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
ApplicationContext
Execute 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 ApplicationContext
the print result:
2)BeanFactory
BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("spring-config.xml"));
BeanFactory
Execute 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 BeanFactoryt
the print result:
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:
Execute BeanFactoryt
(with the operation of obtaining the specified Bean object) and print the result:
Execute BeanFactoryt
(with the operation of obtaining the specified Bean object) and print the result:
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.
ApplicationContext
and BeanFactory
the link:
ApplicationContext
Both BeanFactory
are interfaces, and their subclasses are called when they are used.
Comparison and difference between the two methods: compare and explain from the two aspects of inheritance function and performance.
- 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.
- 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, NoSuchBeanDefinitionException
an exception will be thrown.
2) Obtain by class name
Student student = context.getBean(Student.class);
NoUniqueBeanDefinitionException
There 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 .
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
- Create a Maven project
- Add Spring framework dependency [spring-context]
- Add startup class [Function: Prepare for reading Bean from Spring container later]
2) Storage Bean
- Create a Bean object
- Register the Bean in the Spring container [spring-config.xml configuration file]
3) Read the Bean
- Get the Spring object [ApplicationContext, BeanFactory]
- Obtain the Bean object through the getBean() method of the Spring object [DI operation]
- 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.
- 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.
- 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, NoUniqueBeanDefinitionException
an 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);