Learning of Spring framework

Spring is a very popular Java Web development framework, which is used to solve the complexity of enterprise applications.

  • Spring framework is an open source J2EE application framework, which is a lightweight container for managing the life cycle of bean s
  • Inversion of control - Spring promotes low coupling through a technology called inversion of control (IoC).
  • Aspect oriented - allows cohesive development by separating application business logic from system level services.
  • container
  • Framework - Spring can configure and combine simple components into complex applications.
<!--To import spring of jar package-->
 <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->

1. Why use the Spring framework?

In the previous business, the user's needs will affect the original code, and the source code needs to be modified according to the user's needs.
If the amount of program code is large, the cost of modifying the code once will be very large.
In the traditional object-oriented programming method, the way to obtain an object is generally new, a new object to call
However, in the spring framework, IoC is used. The life cycle of objects is managed by the IoC container provided by the spring framework. All objects are stored in the container, and the control is handed over by the application to the IoC container.
When we need to use it, we can take it directly from the container, which is more convenient and fast

2. What is IoC?

IoC translates into control inversion.
The process of creating objects is changed from active to passive, that is, the created objects are handed over to the IoC container for processing, and the control is reversed, that is, the control is reversed.
IoC theoretically realizes the decoupling between dependent objects with the help of a third party. After encapsulating each object class, these object classes are associated through the IoC container. In this way, there is no direct relationship between objects, but through the IoC container.

3. What is DI?

DI translates into dependency injection.
The so-called dependency injection means that the IoC container dynamically injects a dependency into the object during operation.

In fact, dependency injection (DI) and inversion of control (IoC) are different descriptions of the same thing.
Dependency injection is described from the perspective of program, that is, the application depends on the container to create and inject the external resources it needs;
The control inversion is described from the perspective of the container, that is, the container controls the program, and the container reversely injects the external resources required by the application into the application.
The external resource here can be an external instance object or an external file object.

4. What are the benefits of using IoC/DI?

  • The maintainability is good, which is convenient for unit test, debugging program and fault diagnosis. Each class of the code can be debugged separately without affecting each other. Only by ensuring that its own functions are correct, this is the benefit of low coupling or no coupling between components!
  • In team development, you only need to focus on your own business implementation. Because their own tasks have nothing to do with other people's tasks, their own tasks can be tested separately without relying on other people's components.
  • Good reusability. Common components with universality can be separated and repeatedly applied to other parts of the project or other projects. Of course, this is also the basic feature of object-oriented. IoC better implements this principle and improves the reusability of modules.
    Implementations that conform to the interface standard can be plugged into modules that support this standard!
  • The method of generating objects is changed to external method, that is, the object generation is defined in the configuration file. In this way, when we change an implementation subclass, it will become easier. We can only modify the configuration file. Fully comply with the characteristics of hot plug!

5. Implementation of IoC/DI

The main function of Spring framework is implemented through container. The Spring framework provides two core containers, BeanFactory and ApplicationContext. IoC/DI is usually implemented in two ways: setter injection and constructor injection.

① Spring core container

The two most basic and important packages of the Spring framework are org springframework. beans. Factory (main interface: BeanFactory)
And org springframework. Context (main interface: ApplicationFactory)

The main components of Spring IoC framework include Beans, configuration file and ApplicationContext XML, BeanFactory interface and its related classes, ApplicationContext interface and its related classes

(1) . beans refers to the beans that provide business functions in the project, that is, the beans to be managed by the container. Beans is a common JavaBean and Java class

(2) . Bean management in Spring is carried out in the configuration file. Edit the configuration file in the Spring container to manage the assembly of beans, also known as beans. In fact, the assembly is to tell the container which beans are needed and how the container uses IoC to cooperate them.
The Bean configuration file is an XML file, which can be named ApplicationContext XML or other, generally used to ApplicationContext xml

The configuration file contains Bean of id,Class, property, and its value. Contains one<beans>Element and number<bean>Child element.
Spring IoC The framework can be based on Bean of id from Bean Get the from the configuration file Bean And generate an instance object of the class,
The properties and values of the object are then obtained from the configuration file.
Common configuration file formats are as follows:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

    <!--use Spring Create objects in Spring All become bean
    id=Variable name,It is also a mark to be removed from the program
    class= new Object of
    property Equivalent to setting a value for a property in an object

    <!--use Spring To create an object, in Spring These have become Bean-->

    <bean id="UserDaoImpl" class="com.study.dao.UserDaoImpl"/>
    <bean id="UserDaoImpl1" class="com.study.dao.UserDaoImpl1">
    <!--name The parameters passed in later are those we have created in the entity class. We pass them here value Pass in parameters to assign values to it-->
    	<property name="str" value="Hello World"/>

	<!--ref="id",Incoming id It's what we've created bean of id,General use ref To pass in parameters,
	this bean They are all classes that can be used directly, rather than method classes and entity classes that do not need to pass parameters-->
    <bean id="t" class="com.study.service.UserServiceImpl">
        <property name="str" ref="UserDaoImpl"/>


(3) BeanFactory adopts the factory design mode, namely Bean container mode, which is responsible for reading Bean configuration files, managing the generation and loading of objects, maintaining the dependency between Bean objects and Bean objects, and taking charge of the life cycle of beans.
For simple programs, using BeanFactroy is enough to manage beans, and you can get a lot of convenience in object management.
org. springframework. beans. factory. Bean factory is a top-level interface that contains various methods for managing beans. The Spring framework also provides some classes that implement this interface
org.springframework.beans.factory.xml.XmlBeanFactory is a common implementation class of BeanFactory, which loads beans according to the definition in the configuration file. To create an XmlBeanFactory, you need to pass a FileInputStream object that provides the XML file to the factory.

BeanFactroy factory = new XmlBeanFactory(new FileInptStream("applicationContext.xml"));

The common methods of BeanFactory are as follows:

  • getBean(String name): the object of the Bean can be generated according to the id of the Bean. Generally, it can be used only after forced transformation
  • getBean(String name,Class requiredType): the object of the Bean can be generated according to its id and corresponding class.

(4) The ApplicationContext interface provides a container for advanced functions. Its basic functions are very similar to BeanFactory, but it also has the following functions:

  • Provides a more convenient way to access resource files
  • Support internationalization messages
  • Provides methods for parsing text messages
  • Events can be published, and beans interested in events can accept these events

There are three common implementation classes of ApplicationContext interface:

  • FileSystemXmlApplicationContext: loads the information defined in the context from the xml file in the file system
  • ClassPathXmlApplicationContext: load the information defined in the context from the xml file in the classpath, and treat the file defined in the context as a classpath resource
  • XmlWebApplicationContext: loads the information defined in the context from the xml file in the web system

The FileSystemXmlApplicationContext and ClassPathXmlApplicationContext are used as follows:

ApplicationContext context = new FileSystemXmlApplicationContext("d:/applicationContext.xml");

//Key use
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

The first way is to use the file system to query the configuration file. At this time, the configuration file is located on disk D.
The second is to query the configuration file by using the classpath. At this time, the configuration file is located in the src directory of the project. Generally, the Maven project created by IDEA should be in the resources directory.
FileSystemXmlApplicationContext can only query the configuration file under the specified path. ClassPathXmlApplicationContext can query the configuration file in the whole classpath.

② . IoC/DI implementation mode

There are two main implementation methods: setter() method injection and constructor method injection.

  • Property setter() method injection: IoC container uses setter() method to inject the dependent instance. By instantiating the Bean by calling the no parametric constructor or the non parametric static factory method, we can invoke the dependency injection based on setter() method by calling the setter() method of the Bean. This method is simple, intuitive and easy to understand, so Spring's setting injection is widely used
  • Constructor injection: IoC container uses constructor to inject dependent instances. Dependency injection based on construction method is realized by calling construction method with parameters, and each parameter represents a dependency.

Construction method injection method:
First, you need to have a class without a set method

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

    public User(String name, int age) {
        this.name = name;
        this.age = age;

    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +

1. Subscript assignment

<!--Subscript assignment index Indicates the number of parameters. If not written, the default value is 0-->
    <bean id="user" class="pojo.User">
        <constructor-arg index="0" value="Xiao Ming"/>
        <constructor-arg index="1" value="10"/>

2. Type creation

<!--It is generally used for disorder-->
	<bean id="getInfo" class="User.User">
        <constructor-arg type="java.lang.String" value="Xiao Ming"/>
        <constructor-arg type="int" value="10"/>

3. Parameter name creation (common)

    <bean id="user" class="User">
        <constructor-arg name="name" value="Xiao Ming"/>
        <constructor-arg name="age" value="10"/>

Summary: when the configuration file is loaded, the objects managed in the container have been initialized. If they are created in the container, all the objects in the container will be taken out during operation!

Keywords: Java Spring Container

Added by theorok on Thu, 30 Dec 2021 17:57:04 +0200