I. Inversion of control Ioc

Inversion of Control (IoC), a design principle in object-oriented programming that reduces coupling between computer code. One of the most common is called Dependency Injection, or DI, and another is called Dependency Lookup. With inversion of control, when an object is created, it is passed a reference to the object on which it depends by an external entity that regulates all objects in the system. In other words, dependencies are injected into objects.

The above is the comprehensive introduction of Ioc by Baidu Baike. At the heart of Spring is the Ioc container, through which bean objects can be managed. Ioc inversion of control is actually a way of thinking/programming. In this case, the management of beans is handed over to Spring by the programmer. Instead of new objects, we need to configure the Bean’s corresponding configuration file, which is directly fetched from the Spring container when using its objects.

Second, build Ioc environment based on XML

Import dependence

<dependency>
	<groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.13. RELEASE</version>
</dependency>
Copy the code

Create the Spring configuration file applicationContext.xml and add the constraints


      
<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">
    <! Let spring manage the Bean object.
    <bean id="userMapper" class="com.zxwin.mapper.impl.UserMapperImpl"/>
    <bean id="userService" class="com.zxwin.service.imple.UserServiceImpl"/>
</beans>
Copy the code

test

public class Client {
    public static void main(String[] args) {
       // Get the spring core container object
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        // Get the Bean object from the core container
        UserMapper userMapper = ac.getBean("userMapper", UserMapper.class);
        UserService userService = ac.getBean("userService", UserService.class); System.out.println(userMapper); System.out.println(userService); }}Copy the code

com.zxwin.mapper.impl.UserMapperImpl@464bee09 com.zxwin.service.imple.UserServiceImpl@f6c48ac

The three implementation classes of the core container interface ApplicationContext

  • ClassPathXmlApplicationContext: used to retrieve the classpath configuration file
  • FileSystemXmlApplicationContext: used to obtain any position in the disk configuration file
  • AnnotationConfigApplicationContext: used to read comments to create containers

The difference between the two interfaces of the core container

  • ApplicationContext: It loads the schema immediately upon the policy used to create the container and creates the object as soon as it reads the configuration file. Applies to singleton objects
  • BeanFactory: The policy used to create containers is lazy loading, when objects are used, when objects are created, for multiple objects

Details of Spring’s Bean management

Three ways to create Bean objects

  • Use the default constructor to create the object

    Tags are used in the Spring configuration file and the default constructor is used to create objects when the configuration has no attributes and tags other than ID and class

    <bean id="userMapper" class="com.zxwin.mapper.impl.UserMapperImpl"/>
    Copy the code
  • Create objects using methods in a normal factory (create objects using methods in a method)

    <! Spring creates the InstanceFactory object, using the getService() method to create the UserService object.
    <bean id="instanceFactory" class="com.zxwin.Factory.InstanceFactory"/>
    <bean id="userService" factory-bean="instanceFactory" factory-method="getService"/>
    Copy the code
  • Create an object using a static method in a factory (create an object using a static method in a method)

    <bean id="userService" class="com.zxwin.Factory.InstanceFactory" factory-method="getService"/>
    Copy the code

The scope of the Bean

The scope of the bean is configured on the scope property of the label

The value of the scope property

  • Singleton: Singleton pattern (default)
  • Prototype: Multiple example mode
  • Request: Range of requests applied to web applications
  • Session: The range of sessions applied to the Web application
  • Global-session: specifies the range of sessions that apply to the cluster environment

The life cycle of the Bean

The life cycle of a bean depends on whether it is singleton or multi-instance

  • The singleton pattern life cycle is consistent with the container
    • Born: The object is born when the container is created
    • Die: The object dies when the container is destroyed
  • The multi-case pattern lives as long as the object is always using the object
    • Birth: Containers are created when objects are used
    • Dead: JVM reclaim when this object is not referenced

DI in Spring

Ioc’s role is to reduce dependencies between programs, which we leave to Spring to manage. If the current class has dependencies provided by Spring, we only need to specify this in the configuration file. Maintenance of this dependency is called dependency Injection. The implementation of Ioc relies on DI

DI is popularly known as spring’s operation of assigning values to members when an object is created

Three approaches to dependency injection

Use constructor injection

Use the label inside the label

The attribute values of the tag include

  • Type: Specifies the data type to be injected. Spring matches the corresponding parameter based on the data type
  • Index: Specifies the index to which parameters are to be injected, starting from 0
  • Name: Specifies the name of the parameter to be injected
  • Value: Used to provide both primitive and String values
  • Ref: Specifies other Bean objects
<bean id="diTest" class="com.zxwin.DiTest">
	<constructor-arg name="name" value="zxwin"></constructor-arg>
    <constructor-arg name="age" value="22"></constructor-arg>
    <constructor-arg name="birthday" ref="birthday"></constructor-arg>
</bean>
<bean id="birthday" class="java.util.Date"></bean>
Copy the code
public class DiTest {
    private String name;
    private Integer age;
    private Date birthday;
    public DiTest(String name, Integer age, Date birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday; }}Copy the code

Note: Generally the data to be injected is not easily changed data, such as :service layer call DAO layer can be injected. The above example is for demonstration purposes only

The advantage of using constructor injection is that it is necessary to inject data when retrieving an object, otherwise the object cannot be created successfully

Disadvantages: Changes the way bean objects are instantiated, and even if they are not available, they need to be provided

Use the set method for injection

Use the label inside the label

Attributes of tags

  • Name: Used to specify the name of the set method to be called at injection time
  • Value: Used to provide both primitive and String values
  • Ref: Specifies other Bean objects
<bean id="diTest" class="com.zxwin.DiTest">
    <property name="name" value="zxwin"/>
	<property name="age" value="22"/>
	<property name="birthday" ref="birthday"/>
</bean>
<bean id="birthday" class="java.util.Date"></bean>
Copy the code
public class DiTest {
    private String name;
    private Integer age;
    private Date birthday;
    // Note that it must be set because the 
      
        tag's name attribute calls set
      
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday; }}Copy the code

Advantages of using the set method for injection: There are no restrictions on creating objects, and they can be created directly using the default constructor

Disadvantages: If a member must have a value, we do not call set injection and cannot execute

Using annotation injection

Explain in the notes section

Data types supported by dependency injection

  • Basic types and Strings
  • Other spring-managed bean types
  • Complex type/collection type
public class DiTest {
    private String[] array;
    private List<String> list;
    private Map<String,String> map;
    private Set<String> set;
    private Properties props;

    public void setArray(String[] array) {
        this.array = array;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    public void setSet(Set<String> set) {
        this.set = set;
    }

    public void setProps(Properties props) {
        this.props = props; }}Copy the code
<bean id="diTest" class="com.zxwin.DiTest">
        <! Insert into array -->
        <property name="array">
            <array>
                <value>aaa</value>
                <value>bbb</value>
                <value>ccc</value>
            </array>
        </property>
        <! List -->
        <property name="list">
            <list>
                <value>aa</value>
                <value>bb</value>
                <value>cc</value>
            </list>
        </property>
        <! Insert map -->
        <property name="map">
            <map>
                <entry key="map1" value="aaa"/>
                <entry key="map2" value="bbb"/>
                <entry key="map3" value="ccc"/>
            </map>
        </property>
        <! Insert into set -->
        <property name="set">
            <set>
                <value>a</value>
                <value>b</value>
                <value>c</value>
            </set>
        </property>
        <! Insert property -->
        <property name="props">
            <props>
                <prop key="prop1">a</prop>
                <prop key="prop2">b</prop>
                <prop key="prop3">c</prop>
            </props>
        </property>
</bean>
Copy the code

Note:

The label used to inject the list structural collection

The label used to inject the map structure collection

Tags can be used interchangeably between homologous structures