Spring Framework--IOC/DI

Spring Framework IOC/DI

1. IOC (inversion of Control) Inversion of Control

1. What is inversion of control?

IOC: Inversion of Control. In the past, objects needed to be created by themselves. Now, the operation of object creation is handed over to the spring framework. When using it, you can directly ask the framework. Spring is responsible for the creation and management of all objects, which is called IOC. container.

2. What is the function of the IOC container and what is stored inside?

  • The IOC container is responsible for a series of tasks such as object creation and initialization, including class objects in the data layer and business layer
  • Objects that are created or managed are collectively referred to as ==Bean== in the IOC container
  • Bean objects are placed in the IOC container

3. After the service and dao objects are created in the IOC container, can the program be executed correctly?

  • No, because the service operation needs to rely on the dao object
  • Although there are service and dao objects in the IOC container
  • But the service object has nothing to do with the dao object
  • The dao object needs to be handed over to the service, that is to say, the relationship between the service and the dao object needs to be bound

DI is used to establish the binding relationship between objects and objects in containers like this.

2. DI (Dependency Injection) dependency injection

(1) What is dependency injection?

The whole process of establishing the dependency relationship between beans in the container is called dependency injection. The business layer needs to use the class object of the data layer, which used to be new by itself

Now I am not new, and I rely on others [external actually refers to the IOC container] to inject it

This idea is dependency injection

(2) Which beans in the IOC container need to establish dependencies?

  • This requires programmers to establish a good relationship in advance according to business needs. If the business layer needs to rely on the data layer, the service must establish a dependency relationship with dao. After introducing the concepts of Spring's IOC and DI, we will find that the ultimate goal of these two concepts is :==Full decoupling==, the specific implementation depends on:
  • Managed beans using the IOC container (IOC)
  • Relational binding (DI) of beans with dependencies in the IOC container
  • The final result is: when using an object, not only can it be obtained directly from the OC container, but the obtained bean has already bound all dependencies

An important feature is reflection, which allows the program to dynamically generate objects, execute object methods, and change object properties at runtime. Spring implements injection through reflection

  • Injection method: 1. Set method injection 2. Construction method injection 3. Field injection
  • Injection type: 1. Value type injection 2. Reference type injection

Interface difference

  • BeanFactory, an interface used internally by Spring, is not provided to developers. It will not be created when loading configuration xml parsing, and only when creating objects will getBean
  • ApplicationContext is a sub-interface of BeanFactory, which is powerful and can be used by developers. Objects will be created when the configuration is loaded.

ApplicationContext has some special implementation classes

  • ClassPathXmlApplicationContext, the file name can be written in the src directory
  • FileSystemXmlApplicationContext, in the src directory, must write the absolute path

Implementation:

Reflection is used at the bottom of all Spring frameworks.

First import the jar package

dao layer

BookDao interface

package com.chen.dao;

public interface BookDao {
    void add();
}

BookDaoImpl implementation class

package com.chen.dao.impl;

import com.chen.dao.BookDao;

public class BookDaoImpl implements BookDao {
    @Override
    public void add() {
        System.out.println("BookDaoImpl...add");
    }
}

service layer

BookService interface

package com.chen.service;

public interface BookService {
    void save();
}

BookServiceImpl implementation class

package com.chen.service.impl;

import com.chen.dao.BookDao;
import com.chen.service.BookService;

public class BookServiceImpl implements BookService {
    //BookServiceImpl 依赖 BookDao的对象

    private  BookDao bookDao;
    public String name;
    private int age;
        set方法
        在BookServiceImpl中添加BookDao方法
    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

 使用Spring的API获得Bean实例
    @Override
    public void save() {
        System.out.println("BookServiceImpl...save");
        bookDao.add();
    }
}

BookServiceVip implementation class

package com.chen.service.impl;

import com.chen.service.BookService;

public class package com.chen.service.impl;

import com.chen.service.BookService;

public class BookServiceVip implements BookService {
    @Override
    public void save() {
        System.out.println("BookServiceVip...save");
    }
}
 implements BookService {
    @Override
    public void save() {
        System.out.println("BookServiceVip...save");
    }
}

Test class:

package com.chen.test;

import com.chen.service.BookService;
import com.sun.org.apache.bcel.internal.util.ClassPath;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test01 {
    BookService bookService;

    @Test
    public void tset01(){
        //对家的创建由spring框架创建,此处只需要直接闻IOC空器要
        //1.通过CLassPathXmLApplicationContext加载sprinq.xml获得获得IOC容器
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        //2.从IOC容器中根据名字获得对象
        bookService = (BookService) context.getBean("bookService");
        bookService.save();
    }
}

Spring core configuration file:

<?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=" Index of /schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>

Bean tag basic configuration

Objects used for configuration are created by Spring.

By default, it calls the no-argument constructor in the class. If there is no no-argument constructor, it cannot be created successfully.

Basic attributes:

  • id: the unique identifier of the Bean instance in the Spring container
  • class: The fully qualified name of the Bean

injection method

== basic type

set method injection

Value types are injected with value

Reference types are injected with ref

<?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">

    <!--告诉spring框架,创建管理哪些对象
        id:给创建出来的对象起个名字
        class:要创建对象对应类的全类名
    -->
    <bean id="bookDao" class="com.chen.dao.impl.BookDaoImpl"/>
    <bean id="bookService" class="com.chen.service.impl.BookServiceImpl">
        <property name="bookDao" ref="bookDao"/>
     </bean>
</beans>

3. Commonly used annotations and functions

1.@Component

Class annotation, set the class as a bean managed by spring, the attribute can define the id of the bean, and add it above the class definition. The @Component annotation cannot be added to the interface, because the interface cannot create objects.

 

Step 1: Delete the original XML configuration

<bean id="bookDao" class="com.chen.dao.impl.BookDaoImpl"/>

Step 2: Add @Component annotation on Dao

Step 3: Configure Spring's annotation package scanning

In order for the Spring framework to scan the annotations written on the class, package scanning must be performed in the configuration file.

Correspondence between XML and annotation configuration

2.@ComponentScan

It is used to set the scan path. This annotation can only be added once. Multiple data are in array format, which can replace the scan in the configuration file

3.@Scope

Class annotation, set above the class, set the scope of the object created by this class, can be used to set whether the created bean is a singleton object, the attribute defines the scope of the bean, the default is singleto (singleton), you can fill in the prototype (non-singleton)

6.@Autowired

Attribute annotations, method annotations, and method parameter annotations can be written above the attribute definition, above the standard set method, above the class set method or before the method parameter, to set the value for the reference type attribute

@Autowired can be written on the property or on the setter method. The easiest way to deal with it is to write on the property and delete the setter method

Why can the setter method be deleted?

1. Automatic assembly creates objects based on reflection design and sets values ​​for private properties through violent reflection

2. Ordinary reflection can only get public modified content

3. In addition to public modified content, violent reflection can also obtain private modified content

So there is no need to provide a setter method here

7.@Qualifier

Property annotation or method annotation. Write above the property definition, or above the standard set method or above the class set method. When multiple beans are found in the container according to the type, and the attribute name of the injected parameter is inconsistent with the name of the bean in the container, then you need to use @Qualifier to specify the bean object of which name to inject. The attribute value of the @Qualifier annotation is the name of the bean that needs to be injected. @Qualifier cannot be used independently and must be used with @Autowired.

Guess you like

Origin blog.csdn.net/weixin_67224308/article/details/129821963