Spring Dependency Injection--Introduction to Spring (4)


foreword

In order to consolidate the knowledge learned, the author tried to start publishing some blogs of learning notes for future review. Of course, it would be great if it could help some newcomers learn new technologies. The author is a piece of food. If there are any mistakes in the records in the article, readers and friends are welcome to criticize and correct.
(The reference source code of the blog can be found in the resources on my homepage. If you have any questions during the learning process, please feel free to ask me in the comment area)

1. Introduction to Dependency Injection

1. What is Dependency Injection

  1. In programming, dependency injection is a design pattern that implements inversion of control and is used to solve dependency problems.
  2. A dependency refers to an object that can be exploited. Dependency injection is the passing of dependencies to dependent objects that will be used. The service will become part of the client's state and pass the service to the client without allowing the client to create or find the service.
  3. Dependency injection makes our programming code loosely coupled and easy to manage

2. Classification of dependency injection

  • Thinking: How many ways are there to transfer data in class P?
  1. Common method (set method)
  2. Construction method
  • Thinking: Dependency injection describes the process of establishing dependencies between beans and beans in the container. What if the beans need numbers or strings to run?
  1. reference type
  2. Simple types (basic data types and String )
  • The way of dependency injection
  1. setter injection
    1) simple type
    2) reference type
  2. Constructor injection
    1) simple type
    2) reference type

3. Advantages of Dependency Injection

  1. Reduce dependencies: Dependency injection can eliminate or reduce unnecessary dependencies between components. To reduce the impact of component changes
  2. Enhancing Reusability: Reducing component dependencies can enhance component reusability. If different implementations of an interface are required in different contexts, or simply different configurations of the same implementation, the component can be configured to use that implementation. No code changes required.
  3. Increases testability of code: Dependency injection also increases testability of components. When dependencies can be injected into components, it means that mock implementations of those dependencies can be injected. Mock objects are used for testing as a substitute for the actual implementation, and the behavior of mock objects can be configured
  4. Enhanced code readability: Dependency injection moves dependencies to a component's interface. Makes it easier to see which of your components have dependencies, making your code more readable.
  5. Reduce dependency carrying: Dependency carrying creates a lot of "noise" in the code, making it difficult to read and maintain, and making components harder to test. Dependency injection can reduce the use of dependency carrying and static singletons, and can perfectly connect components together

1. Setter injection

1. Dependency Injection – Setter injects the reference type step method (the DI entry case uses the setter to inject the reference type)

insert image description here(代码见DI入门案例)

2. Discuss referencing multiple reference objects (coded on the basis of DI entry code)

  • Create and write the UserDao interface under the dao package
package org.example.dao;

public interface UserDao {
    
    
    public void save();
}

  • Create and write the UserDaoImpl implementation class under the impl package
package org.example.dao.impl;

import org.example.dao.UserDao;

public class UserDaoImpl implements UserDao {
    
    
    public void save() {
    
    
        System.out.println("user dao save ...");
    }
}

  • Setter injects UserDao into the BookServiceImpl implementation class
public class BookServiceImpl implements BookService{
    
    
    private BookDao bookDao;
    private UserDao userDao;
    //setter注入需要提供要注入对象的set方法
    public void setUserDao(UserDao userDao) {
    
    
        this.userDao = userDao;
    }
    //setter注入需要提供要注入对象的set方法
    public void setBookDao(BookDao bookDao) {
    
    
        this.bookDao = bookDao;
    }

    public void save() {
    
    
        System.out.println("book service save ...");
        bookDao.save();
        userDao.save();
    }
}

  • Configure the bean of userDAO in the core configuration class applicationContext and inject it into BookService

insert image description here

  • Execute mock test class App2

insert image description here
(From the running results, you can see that multiple reference types can be injected with setters)

3. Dependency Injection – Setter Injection Step Method of Common Types

insert image description here

4. Provide two variables in BookDaoImpl and provide corresponding setter methods (take BookDaoImpl as an example)

public class BookDaoImpl implements BookDao {
    
    

    private String databaseName;
    private int connectionNum;
    //setter注入需要提供要注入对象的set方法
    public void setConnectionNum(int connectionNum) {
    
    
        this.connectionNum = connectionNum;
    }
    //setter注入需要提供要注入对象的set方法
    public void setDatabaseName(String databaseName) {
    
    
        this.databaseName = databaseName;
    }

    public void save() {
    
    
        System.out.println("book dao save ..."+databaseName+","+connectionNum);
    }
}

  • Inject ordinary variables into the configuration in the core configuration class applicationContext.xml file

insert image description here

  • The running result of the simulation test class App2

insert image description here

2. Constructor injection

(Coding on the basis of dependency injection-setter injection, delete the code related to dependency injection, see the code respr_diconstouctor uploaded on the personal homepage for details)

1. Dependency Injection – Step method for constructor injection of reference types

insert image description here

2. Provide a constructor in the BookService class

public class BookServiceImpl implements BookService {
    
    
    //5.删除业务层中使用new的方式创建的dao对象
    private BookDao bookDao;

    //提供构造方法
    public BookServiceImpl(BookDao bookDao) {
    
    
        this.bookDao = bookDao;
    }

    public void save() {
    
    
        System.out.println("book service save ...");
        bookDao.save();
    }

}

3. Inject BookDao related beans into the core configuration class

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

    <bean id="bookDao" class="org.example.dao.impl.BookDaoImpl"/>

    <bean id="bookService" class="org.example.service.impl.BookServiceImpl">
        <constructor-arg name="bookDao" ref="bookDao"/>
    </bean>

</beans>

4. Simulate the running results of the test class App2 (similarly, constructor injection can inject multiple reference types, and relevant codes are omitted here)

insert image description here

5. Dependency Injection – Steps and methods for constructor injection of common types

insert image description here

6. Define two variables in BookDao and write the corresponding constructor method

public class BookDaoImpl implements BookDao {
    
    
    private String databaseName;
    private int connectionNum;

    public BookDaoImpl(String databaseName, int connectionNum) {
    
    
        this.databaseName = databaseName;
        this.connectionNum = connectionNum;
    }

    public void save() {
    
    
        System.out.println("book dao save ..."+databaseName+","+connectionNum);
    }
}

7. Configure related properties in the core configuration file

  • Method 1: Inject according to the parameter name of the constructor

insert image description here

  • Method 2: Inject according to the parameter type of the constructor

insert image description here

  • Method 3: Inject according to the parameter position of the construction method

insert image description here

8. Simulation test class App2 running results

insert image description here

  1. Choice of Dependency Injection

insert image description here

3. Automatic assembly

1. Basic knowledge of automatic assembly

  1. We have learned how to use elements to declare beans and inject them by using the and elements in the XML configuration file
  2. The Spring container can autowire relationships between collaborating beans without using and elements, which helps reduce the amount of XML configuration that is written for a large Spring-based application
  3. The following autowiring patterns, which can be used to instruct the Spring container to use autowiring for dependency injection. You can specify the autowire mode for a bean definition using the element's autowire attribute
model describe
no This is the default setting, which means there is no autowiring and you should use explicit bean references for wiring. You don't have to do anything special for the connection. You have already seen this in the dependency injection chapter.
byName (by name) Autowired by property name. The Spring container sees the bean's autowired property set to byName in the XML configuration file. It then tries to match and concatenate its properties with properties of beans of the same name defined in the configuration file.
byType (by type) Autowired by attribute data types. The Spring container sees the bean's autowired property set to byType in the XML configuration file. Then if its type matches an exact bean name in the configuration file, it will try to match and wire the property's type. If there is more than one such bean, a fatal exception will be thrown.
constructor Like byType, but the type applies to constructor argument types. A fatal error will occur if there is no bean of the type of the constructor parameter in the container.
autodetect (not supported in version 3.0) Spring first tries to wire using autowiring via the constructor, if it doesn't, Spring tries to autowire via byType.

可以使用 byType 或者 constructor 自动装配模式来连接数组和其他类型的集合

2. Coding on the basis of the introductory case (see the spring code resource respr_autowire module on the personal homepage for details)

insert image description here

3. Automatic assembly

  • manual configuration

insert image description here

  • Autowiring by type (byType)

insert image description here

需要提供setter方法,ioc通过setter入口给bean

insert image description here

  • assemble by name

要确保BookDao装配bean的id与BookService中的其中一个属性名对应上

insert image description here

  • Depends on autowiring features

insert image description here

  • Collection injection (rarely used) (array, List, Set, Map, properties)

  • Create a new BookDao2 interface and its implementation class

package org.example.dao;

public interface BookDao2 {
    
    
    public void save();
}

public class BookDaoImpl2 implements BookDao2 {
    
    

    //数组
    private int[] array;
    //列表
    private List<String> list;
    //集合
    private Set<String> set;
    //图
    private Map<String,String> map;
    //properties
    private Properties properties;
    //提供对应的setter方法作为ioc提供bean的入口
    public void setArray(int[] array) {
    
    
        this.array = array;
    }

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

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

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

    public void setProperties(Properties properties) {
    
    
        this.properties = properties;
    }
    //编写测试方法
    public void save() {
    
    
        System.out.println("book dao save ...");

        System.out.println("遍历数组:" + Arrays.toString(array));

        System.out.println("遍历List" + list);

        System.out.println("遍历Set" + set);

        System.out.println("遍历Map" + map);

        System.out.println("遍历Properties" + properties);
    }
}

  • Writing core configuration files
<?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">

<!--    <bean id="bookDao" class="org.example.dao.impl.BookDaoImpl"/>-->

<!--    <bean id="bookService" class="org.example.service.impl.BookServiceImpl" autowire="byName"/>-->

    <bean id="bookDao2" class="org.example.dao.impl.BookDaoImpl2">

    <!--数组注入-->
    <property name="array">
        <array>
            <value>100</value>
            <value>200</value>
            <value>300</value>
        </array>
    </property>
    <!--list集合注入-->
    <property name="list">
        <list>
            <value>itcast</value>
            <value>itheima</value>
            <value>boxuegu</value>
            <value>chuanzhihui</value>
        </list>
    </property>
    <!--set集合注入-->
    <property name="set">
        <set>
            <value>itcast</value>
            <value>itheima</value>
            <value>boxuegu</value>
            <value>boxuegu</value>
        </set>
    </property>
    <!--map集合注入-->
    <property name="map">
        <map>
            <entry key="country" value="china"/>
            <entry key="province" value="henan"/>
            <entry key="city" value="kaifeng"/>
        </map>
    </property>
    <!--Properties注入-->
    <property name="properties">
        <props>
            <prop key="country">china</prop>
            <prop key="province">henan</prop>
            <prop key="city">kaifeng</prop>
        </props>
    </property>
    </bean>

</beans>
  • Simulate test class writing and running results

insert image description here

Fourth, spring entry summary

1. IOC container related

insert image description here

2. bean-related

insert image description here

3. Dependency injection related

insert image description here

4. Spring integrates Junit

insert image description here

Summarize

Everyone is welcome to leave a message for exchange and criticism. If the article is helpful to you or you think the author's writing is not bad, you can click to follow, like, and bookmark to support.
(The reference source code of the blog can be found in the resources on my homepage. If you have any questions during the learning process, please feel free to ask me in the comment area)

Guess you like

Origin blog.csdn.net/HHX_01/article/details/131826578