Spring's flip of control (IOC) and dependency injection (DI)

SpringIOC

That is, Inversion of Control, abbreviated as IOC, means that objects are managed by the Spring IoC container, rather than directly controlled by program code in traditional implementations.

  • Manage beans using IOC containers (IOC)

  • Bind dependent beans in the IOC container

The final goal achieved: when using objects, not only can they be obtained directly from the IOC container, but once the obtained beans have dependencies, they have already been bound.

Why use IOC?

Because the coupling degree of the code we wrote before was relatively high. For example, in one of our projects, the class was changed, and the place where it was called to create the object also needed to be changed. This led to a series of problems. Retesting, Redeploying, recompiling, re-releasing, these all have costs. So we pursue a low-coupling and high-cohesion approach.

Solution: When using objects, do not actively use new to generate objects in the program, and convert them to externally provided objects;

From BookDao bd = new BookDao();

Convert to BookDao bd;

This idea is called IOC (Inversion of Control). Inversion of control means that the code does not need to be created to create the object. The control of the object is transferred from the program to the outside. This idea is called inversion of control.

What is the ultimate goal of IOC and DI?

IOC and DI have only one main purpose: full decoupling

How does spring implement IOC and DI ideas?

  • Spring provides a container, called an IOC container, which serves as the "outside" of the IOC idea. This container is the Core Container;

  • The IOC container is responsible for a series of tasks such as object creation and initialization. The created or managed objects are collectively called Beans in the IOC container.

  • When other classes are also used in a class, the entire process of establishing dependencies between beans in the container is called DI (Dependence Injection) dependency injection.

    The IOC container directly binds the beans used in multiple associations to you. The binding process is called dependency injection.

Some frequently asked questions:

What does the IOC manage? (Service and Dao)

How to inform the IOC container about managed objects? (via configuration)

The managed object is handed over to the IOC container. How to obtain the IOC container? (via interface)

After the IOC container is obtained, how to obtain the beans from the container? (interface method)

Which coordinates are imported using spring? pom.xml

 How does spring implement IOC and DI specifically?

Generally speaking, it is divided into two methods: XML configuration file   and  annotation implementation

1. XML-based management

We manage beans in spring.xml. In beans, we manage and configure each object that needs to be used.

(1) What is a bean?

Bean refers to the object managed by spring, which is different from our own new object. Spring can add additional functions to it.

Introduction to properties in beans:

  1. id: Generated object name class full class name

  2. name: Object alias, it can be multiple, separated by spaces or "," or ";", but we still recommend using id

  3. scope: defines how many beans are created

  • singleton (default value): There is only one bean instance in Spring, singleton mode.

    Why default singleton?

    Because the objects managed by spring for us, such as dao and service, can be reused, we do not need to create a new one every time.

    Which beans are suitable for management by the container?

    Made once and used again and again:

    Presentation object

    Business layer objects

    data layer object

    tool object

    Are those beans not suitable for container management?

    Domain object that encapsulates entities

  • prototype: When the prototype getsBean(), it will call new Bean()

  • request: Each http request will create a bean, only used in the WebApplicationContext environment

  • Session: The same httpsession shares a Bean, and different Sessions use different Beans. The usage environment is the same as above.

    How to inject data when creating an object:

    Set method injection: Inject in the set method

    Constructor injection: injection in bean

        <bean id="admin" class="com.ffyc.spring.model.Admin">
            <property name="account" value="1"></property>
            <property name="id" value="2"></property>
        </bean>

Property is to assign values ​​to the properties of this bean object or dependency injection. name indicates which specific property, ref indicates which bean corresponds to the reference (dependency injection), and value sets the default value (for basic types)

(2) After we configure the bean in the xml file, how do we use it?

 Write a class to get the IOC container through the configuration file just now, and then get the object through the container.

(3) How is the bean created?

Three ways to instantiate beans:

1. Provide accessible constructors

In fact, just provide a no-parameter construct in the class

Beans are essentially objects, and spring creates beans using the no-argument constructor.

After we privatize the constructor, the container can still call the constructor to create an object. You must know that when we used a new object, the private constructor would definitely not work. So how does spring call it? The answer is reflection mechanism

2. Instantiate beans using static factories

First, you need to create a factory to produce beans, then configure the factory in the configuration file and let spring manage the factory.

(Note: In the early days, decoupling was often done through factories)

3. Instance factory initialization bean
4. Spring has specially optimized method 3 and has a standard implementation.

(4) Bean life cycle?

Life cycle: the complete process from creation to death

Bean life cycle: the entire process of a bean from creation to destruction

  • Initialize container

    1. Create object (memory allocation)

    2. Execute constructor

    3. Perform attribute injection (set operation)

    4. Execute bean initialization method

  • use beans

    Perform business operations

  • Close/destroy container

    Execute bean destruction method

(5) Bean life cycle control ?

Life cycle control is to do something after the bean is created and before it is destroyed.

(6) Implementation of dependency injection (DI) (manual implementation)

DI is the entire process of establishing dependencies between beans in the container when other classes are used in the class, which is called DI (Dependence Injection) dependency injection. (In fact, it is to assign an initial value to this class)

1.Setter method injection

First write the set method:

Then configure:

 2.Constructor injection

First write the constructor:

 Then configure:

 

Choice of injection method:

 In short: it is recommended to use setters when writing yourself. Third-party technology depends on the situation. Constructor injection is more rigorous.

(7) Third-party bean management

The beans we manage above are all classes created by ourselves. So what should we do if we want to manage external third-party classes, which are classes imported from maven?

In fact, it is also necessary to configure the bean, transfer the management rights to the IOC container management, and then perform dependency injection (assign initial value).

For example, an object connected to a database:

The premise is to import the maven package first and then configure it in the configuration file

 The above are the issues we should pay attention to when using xml configuration~

Guess you like

Origin blog.csdn.net/weixin_52394141/article/details/131614284