Spring 6 [IoC/DI in Spring Framework, the advantages and disadvantages of IoC/DI, the first Spring Framework case] (2) - comprehensive detailed explanation (learning summary --- from entry to deepening)

Table of contents

3. IoC/DI in Spring Framework

4. What are the specific implementation frameworks of IoC?

5. Advantages and disadvantages of IoC/DI 

6. Specific application scenarios of IoC/DI in the project

Four, BeanFactory and ApplicationContext 

5. The first Spring Framework case


3. IoC/DI in Spring Framework

Since we want to learn about the implementation of the IoC/DI principle in the Spring Framework, we have no official document authority no matter what we say.

The official Spring Framework documentation explains IoC as follows: https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core 

1. From the interpretation of the IoC container in the official Spring Framework document, it can be seen that the following points:

2. Emphasize that IoC is also called DI. (IoC is also known as dependency injection (DI))

3. Officially, in order to prevent confusion between the names of IoC and IoC Container. More with DI as the first name. The container is called IoC Container (IoC container)

4. Emphasize that IoC is definitely not an object instantiated by an IoC container, but a process. The process from instantiating the object from the IoC container to injecting other objects that the object depends on inside the IoC container.

5. There are two ways for the IoC container to instantiate objects: through the construction method and through the factory design pattern.

6. BeanFactory and ApplicationContext are used as the interface type of the IoC container in Spring. ApplicationContext is a sub-interface of BeanFactory, which is more powerful.

7. All objects managed inside the IoC container are collectively called beans, and a single object is called a bean. 

The picture below is the official explanation of DI, URL: https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-collaborators

It can be seen from the interpretation of DI in the official Spring Framework document, as follows:

1. Emphasize that DI is also called IoC (hence the name, Inversion of Control).

2. DI is a process (process), definitely not injecting an object into another object is DI. Its explanation is the same as IoC, the process from instantiating objects to injecting objects into other objects is DI.

3. Using DI can realize object decoupling and make the code clearer. You no longer need to manage the objects you depend on, and you don't need to know the location and type of dependencies. (Second paragraph in English)

4. There are two ways to implement DI: Constructor-based dependency injection and Setter-based dependency injection 

4. What are the specific implementation frameworks of IoC?

The framework for the specific implementation of IoC by the Java system:

Lightweight: Spring Framework, Guice, Pico Container, Avalon, HiveMind

Heavyweight: EJB

.Net embodies the framework for the specific implementation of IoC:

Spring.net、 Autofac 、Castle Windsor 、Unity

Some of the above content may not have been heard by ten-year-old Java programmers. For friends, we only need to master the Java field and use the most used IoC implementation framework, Spring Framework.

5. Advantages and disadvantages of IoC/DI 

advantage:

1. Decoupling. The instantiation, assembly, and management of objects are completely handed over to the IoC container. Achieve decoupling between objects.

2. Suitable for medium and large projects. For complex projects, the object relationship may be complicated, and the IoC container can manage these objects well.

shortcoming:

1. The process of instantiating and injecting objects to the container is reflection. Compared with hard-coded instantiation, reflection has a certain performance loss. Fortunately, in some scenarios that require frequent instantiation, the Spring Framework can use the singleton design pattern to reduce the number of bean instantiations.

2. Not suitable for micro and small projects. For object decoupling, in the case of uncomplicated object relationships, a large amount of XML configuration or annotations are required, which increases the workload.

6. Specific application scenarios of IoC/DI in the project

The main function of IoC/DI is to manage the instantiation of objects and the dependencies between objects. In the project, the layer objects that need to be instantiated before, and the entry classes that need to instantiate the framework or toolkit can be handed over to the Spring container for management.

1. Layer objects: Java projects are all layered development. All layer objects are managed by the IoC container, and these layer objects can be injected into other objects managed by the IoC container anytime and anywhere. For example: PeopleMapper interface proxy object, PeopleDaoImpl, PeopleServiceImpl

2. Integrate other technologies: The IoC container can manage the entry of other technologies. When starting the IoC container, manage the bean. Such as: SqlSessionFactory and SqlSession in MyBatis, etc.

The corresponding common classes PeopleMapper and PeopleServiceImpl in the figure below can be handed over to the Spring container for management. Objects placed into containers can directly depend on each other. But Servlet can only be managed by Tomcat (created by Tomcat to help instantiate), so the Spring container cannot manage Servlet. But Servlet can fetch objects from Spring container.

Four, BeanFactory and ApplicationContext 

A very important part of the IoC/DI implementation process is the IoC Container. The IoC container must be created to continue to do the following things. The types of IoC Container in the Spring framework are BeanFactory and ApplicationContext. So you must first understand what these two things are before you can write the first Spring framework case. Otherwise, even if it is written according to the video, it is still following the gourd. When learning IoC/DI above, I saw that the official introduced the difference between BeanFactory and ApplicationContext directly when introducing IoC.

URL: https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-int roduction

Tidy up:

1. BeanFactory is the top-level interface of the IoC container in the Spring framework. It provides the core functions of the IoC container.

2. ApplicationContext is a sub-interface of BeanFactory, and ApplicationContext has all the functions of BeanFactory.

3. ApplicationContext has more functions than BeanFactory

* AOP function

* Internationalization (MessageSource)

* Access resources such as URLs and files (ResourceLoader)

* Message sending mechanism (ApplicationEventPublisher)

* Spring integrated Web time function. 

In addition to the difference between the two directly given in the above documents, when using BeanFactory, all beans are instantiated when they are acquired by default. When using ApplicationContext, all beans will be instantiated immediately when the IoC container starts. At this time, some friends may be a little confused, so which interface should be used as the IoC container type? In fact, the official has given a clear explanation on this issue.

网址: https://docs.spring.io/spring-framework/docs/current/reference/html/core.ht ml#context-introduction-ctx-vs-beanfactory 

The official has clearly stated that it is recommended to use ApplicationContext, so we will use ApplicationContext or its subinterfaces later. Although BeanFactory is not recommended, we can see what methods are in the BeanFactory interface. 

As you can see from the figure above, the main function of BeanFactory is to obtain the beans in the container. When obtaining, it can be obtained by type or by name. It also supports generics and can control the type of Bean after obtaining. So BeanFactory only provides the most basic functions of the IoC container. That is: IoC/DI function.

There are many related interfaces and implementation classes in the BeanFactory hierarchy (Hierarchy) 

So I use a clearer picture to show these two interfaces and commonly used implementation classes.

It can be seen that ApplicationContext inherits 6 more parent interfaces than BeanFactory. These six parent interfaces are more functions of ApplicationContext than BeanFactory. Although I don't quite understand what these 6 interfaces mean now, don't worry, you can look back after you learn it. Now you only need to know that ApplicationContext is more powerful than BeanFactory.

Finally, let's look at ClassPathXmlApplicationContext. Because ApplicationContext is an interface, it cannot be instantiated. Only this implementation class can be instantiated. To instantiate a class, you need to call the constructor of the class. The construction method selected in the figure below with a String type parameter is our common one, and the parameter is the path of the Spring framework configuration file. 

Then you can get the Bean object in the container through getBean inherited from BeanFactory.

Therefore, if you want to create an IoC container in the Spring framework and get the Bean from the container, the code is relatively simple

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
People peo = applicationContext.getBean("peo", People.class);
System.out.println(peo);

 Finally, attach the way of BeanFactory container creation.

Before Spring 3.1, BeanFactory was instantiated through XmlBeanFactory, but XmlBeanFactory no longer exists in the current Spring Framework 6.

FileSystemResource fsr = new
FileSystemResource("D:\\idea\\idea2022ws\\summer\\src\\main\\resources\\applicat
ionContext.xml");
XmlBeanFactory xmlBeanFactory = new XmlBeanFactory(fsr);
People peo = xmlBeanFactory.getBean("peo",People.class);
System.out.println(peo);

 Starting from Spring 3.1 version, use DefaultListableBeanFactory and XMLBeanDefinitionReader to replace the above writing.

DefaultListableBeanFactory defaultListableBeanFactory = new
DefaultListableBeanFactory();
XmlBeanDefinitionReader xmlBeanDefinitionReader = new
XmlBeanDefinitionReader(defaultListableBeanFactory);
xmlBeanDefinitionReader.loadBeanDefinitions(new
FileSystemResource("D:\\idea\\idea2022ws\\summer\\src\\main\\resources\\applicat
ionContext.xml"));
People peo = defaultListableBeanFactory.getBean("peo", People.class);
System.out.println(peo);

5. The first Spring Framework case

Any framework is divided into the following 5 steps from the establishment of the project to the test results, and these 5 steps belong to the formula. Avoid writing code without ideas.

The Spring framework does not depend on the Servlet container (Tomcat), so a normal Maven project without a template is fine. The Spring framework provides XML, annotations, and Java Config three ways to configure projects. First of all, we start learning from the XML method.

1. Create a project and add dependencies 

Create a normal Maven project and name it summer (since the Spring framework is called spring, we call it summer)

Add the most basic dependencies of the Spring project to the pom.xml of the project.

A Spring project must contain:

1. spring-context. jar. The spring context depends on the following four jars.

2. spring-core. jar. Spring core jar package. It depends on spring-jcl.jar

3. spring-aop. jar. Spring AOP basic support. (not required)

4. spring-expression. jar. Spring's expression language support.

5. spring-beans. jar. Bean management of the Spring container.

6. spring-jcl. jar. The Spring 4 version is common-logging.jar. Starting from 5, Spring has encapsulated the log itself. 

So if you want to use the Spring framework in Maven, you only need to import spring-context in the project, and other jar packages can be imported according to the Maven dependency transitivity. The latest version of Spring Framework is 6.0.6 at the time of document creation. So the following dependencies import the latest 6.0.6 version. The spring-context coordinates can go to https://mvnrepository.com/ to search for spring-context

<dependencies>
   <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>6.0.6</version>
   </dependency>
</dependencies>

After adding dependencies in the project's pom.xml, you need to manually update:

Note on the version number of the Spring Framework: Starting from Spring Framework 5.3.0, the version numbers of all Spring submodules no longer end with .RELEASE. For example: before it was 5.2.22.RELEASE For example: now it is 6.0.6 

2. Create a class at will 

Create a class under the project as a class to test the Spring IoC/DI function.

In the example it is called com.tong.pojo.People

public class People {
private int id;
private String name;
// 没有粘贴getter/setter、toString、无参构造方法、全参构造方法
}

3. Create a Spring configuration file

Right mouse button under src/main/resources -> New -> XML Configuration File -> Spring Config. Be sure to pay attention: this will only be available if the spring-context dependency is added correctly.

Tips: The file name is not mandatory. The name of the configuration file in the official example is applicationContext.xml, so we also call the Spring configuration file applicationContext.xml

<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- id:bean的名称 class:类型全限定路径 -->
<bean id="peo" class="com.tong.pojo.People"></bean>
</beans>

 3.1 After creating Spring Config, it prompts that the project does not have this configuration file. The solution

When the file is created, it prompts "Application context not configured for this file". In fact, this problem does not affect the operation of the program. But if the friends have to struggle with this problem, we can also solve this problem.

The first way: Manually change the project configuration (invalid after Reload) 

Select IDEA menu File -> Project Structure...

Add configuration files as shown. Modules -> Spring under the project name (summer) -> Click +

After checking the configuration file, click Apply first, and then click the OK button

Then go to modify the content of applicationContext.xml and find that the above warning message is gone.

The second method: shortcut (failure after Reload) 

Click the prompt message directly: Configure application context -> Create new application context

The pop-up box is the same as the pop-up box for adding configuration files when configuring manually above. It's just that the configuration file is automatically selected here. Just click the OK button below.

The third method: Create a configuration file template (failure after reload) 

If you don't want to have a warning message after creating the file, you can also create a configuration file template

(1) Copy the document header and tags of the XML file. don't label inside

(2) Click the first File -> Settings... in the IDEA menu

(3) Fill in the template according to the picture

Name: is the template name. The template content will be found by this name in the future.

Extension: file extension. When creating a file, it can end with .xml. If there is no .xml ending, IDEA will help to add it. 

 

Thorough solution (still valid after reload) 

 Click the warning message directly, the small screw icon on the right, and click the first "Edit inspection profile setting" in the pop-up box

In the pop-up box, uncheck "Incorrect XML application context" and click OK. At this time, no matter whether it is to modify the content of the XML file. Or the Reload project, no warning message pops up

Because there is no warning message, the warning screw icon cannot be clicked again. To find the above interface, you need to find it through: IDEA menu File -> Editor -> Inspections -> Spring -> Spring Core -> Setup 

4. Create a test class

Create a test class to test Spring functionality. 

package com.tong.test;
import com.tong.pojo.People;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
    public static void main(String[] args) {
    // IoC: 对象实例化和给对象注入依赖内容的过程都交给IoC容器完成的过程。
    // 拆分讲解:先讲解如果让IoC容器对类实例化。
    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    /*
    getBean():
    第一个参数:IoC容器中Bean的ID
    第二个参数:返回值类型。没有第二个参数返回值为Object类型
    */
    People peo = ac.getBean("peo", People.class);
    System.out.println(peo);
   }
}

5. Observation results

It is found that the People object can be successfully created, but all properties in the object have not been assigned

Guess you like

Origin blog.csdn.net/m0_58719994/article/details/131748941