Example of IOC container and DI dependency injection

Example of IOC container and DI dependency injection

In-depth understanding of IOC

Let's first deepen our understanding of IOC through a few questions

  • (1) Spring uses the IOC container to manage bean objects. What do we mainly manage?

Mainly manage the class objects used in the project, such as (Service layer object and Dao layer object)

  • (2) How to inform the IOC container of the managed object?

use configuration file
Spring configuration file

  • (3) The managed objects are handed over to the IOC container. If we want to get objects from the container, how do we get the IOC container?

The Spring framework provides the corresponding interface

  • (4) After the IOC container is obtained, how to obtain the bean from the container?

Call the method in the corresponding interface provided by the Spring framework

  • (5) Which coordinates are imported using Spring?

To use other people's things, you need to add corresponding dependencies in pom.xml

IOC example:

Next, let's get acquainted with the process completely:

1. First, we need to import Spring dependencies to make it a Spring project

Introducing Spring

2. Create a configuration file and configure the Bean

configuration bean

3. It can be referenced in the main program
use

We said before that the result of full decoupling is that the data layer objects are no longer retained in the business layer, but obviously, our code is still new in the service layer. Decoupling.
incomplete decoupling

DI in-depth understanding

To achieve dependency injection, you must manage beans based on IOC

-(1) Is the Dao object created in the form of new retained in the Service?

Need to delete, and finally use the bean object in the IOC container

  • (2) How do the Dao objects needed in the Service enter into the Service?

Provide a method in the Service, so that Spring's IOC container can pass in the bean object through this method

  • (4) How to describe the relationship between Service and Dao?

Also use the configuration file

DI example

1. Delete the new dao layer object in the service layer and provide the corresponding set method in the service layer

这一步相当于删掉业务层的dao对象并告诉service层需要的dao对象该如何获取(通过set方法),结束时,我们还不知道二者关系,需要利用配置文件建立关系
Modify the service layer

2. Modify the configuration file to establish the relationship between the service layer and the dao layer

configuration modification

The article mentions code tarball resource

Guess you like

Origin blog.csdn.net/weixin_45696320/article/details/130178983