Learn more about dependency Injection (DI)

“This is the 16th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

About the author

  • The authors introduce

🍓 Blog home Page: author home page 🍓 Introduction: High-quality creator in the JAVA field 🥇, a junior student 🎓, participated in various provincial and national competitions during school, and won a series of honors 🍓, Ali Cloud expert blogger, 51CTO expert blogger, follow me: Pay attention to my learning materials, document download all have, regularly update the article every day, inspirational to do a JAVA senior program ape 👨💻


Dependency Injection (DI)

  • Dependency Injection (DI)

  • Dependency: The creation of Bean objects depends on the container. The dependent resource of the Bean object

  • Injection: Refers to the resource on which the Bean object depends, which is set and assembled by the container.

8.1 Constructor injection

Synchronize to the IOC object creation approach of Spring5 with the easy start SSM architecture

8.2 SET Injection (key)

The set method must be capitalized with the first letter of the set + attribute. If the attribute is of Boolean type, there is no set method, is.

Test the POJO class:

Address.java

package com.spring.pojo;

/ * * *@ProjectName: Spring5study
 * @Package: com.spring.pojo
 * @ClassName: Address
 * @Author: Shengrui Zhang *@Date: 2022/2/2 1 *@Version: 1.0 * /
public class Address {
    private String address;

    public String getAddress(a) {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString(a) {
        return "Address{" +
                "address='" + address + '\' ' +
                '} '; }}Copy the code

Student.java

package com.spring.pojo;

import java.util.*;

/ * * *@ProjectName: Spring5study
 * @Package: com.spring.pojo
 * @ClassName: Student
 * @Author: Shengrui Zhang *@Date: 2022/2/2 and *@Version: 1.0 * /
public class Student {
    private String name;
    private Address address;
    private String []course;
    private List<String> hobbies;
    private Map<String,String> books;
    private Set<String> games;
    private String girlfriends;
    private Properties info;

    public String getName(a) {
        return name;
    }

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

    public Address getAddress(a) {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String[] getCourse() {
        return course;
    }

    public void setCourse(String[] course) {
        this.course = course;
    }

    public List<String> getHobbies(a) {
        return hobbies;
    }

    public void setHobbies(List<String> hobbies) {
        this.hobbies = hobbies;
    }

    public Map<String, String> getBooks(a) {
        return books;
    }

    public void setBooks(Map<String, String> books) {
        this.books = books;
    }

    public Set<String> getGames(a) {
        return games;
    }

    public void setGames(Set<String> games) {
        this.games = games;
    }

    public String getGirlfriends(a) {
        return girlfriends;
    }

    public void setGirlfriends(String girlfriends) {
        this.girlfriends = girlfriends;
    }

    public Properties getInfo(a) {
        return info;
    }

    public void setInfo(Properties info) {
        this.info = info;
    }

    @Override
    public String toString(a) {
        return "Student{" +
                "name='" + name + '\' ' +
                ", address=" + address +
                ", course=" + Arrays.toString(course) +
                ", hobbies=" + hobbies +
                ", books=" + books +
                ", games=" + games +
                ", girlfriends='" + girlfriends + '\' ' +
                ", info=" + info +
                '} '; }}Copy the code

Constant injection


      
<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="student" class="com.spring.pojo.Student">
        <property name="name" value="Director"/>
    </bean>

</beans>
Copy the code

Testing:

import com.spring.pojo.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/ * * *@ProjectName: Spring5study
 * @Package: PACKAGE_NAME
 * @ClassName: MyTest
 * @Author: Shengrui Zhang *@Date: 2022/2/2 12:57
 * @Version: 1.0 * /
public class MyTest {
    @Test
    public void test1(a){
         ApplicationContext context= new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student"); System.out.println(student.getName()); }}Copy the code

Results:

2. Bean injection

<! -- Bean injection mode -->
    <bean id="address" class="com.spring.pojo.Address">
        <property name="address" value="Shanxi"/>
    </bean>

    <! -- Constant injection mode -->
    <bean id="student" class="com.spring.pojo.Student">
        <property name="name" value="Director"/>

        <! -- Bean injection mode -->
        <! The addresss Bean injection is mapped to the addresss Bean injection.
        <property name="address" ref="address"/>
	</bean>
Copy the code

3. Array injection

 <! -- Array injection mode -->
        <property name="course">
            <array>
                <value>The data structure</value>
                <value>Database Principles</value>
                <value>The operating system</value>
                <value>Computer network</value>
            </array>
        </property>
Copy the code

4. List injection

<! -- List insert -->
        <property name="hobbies">
            <list>
                <value>Play the game</value>
                <value>Knock on the code</value>
                <value>tourism</value>
            </list>
        </property>
Copy the code

5. Map injection

<! Insert entry entity key value into Map -->
        <property name="books">
            <map>
                <entry key="10001" value="Object-oriented Programming A"/>
                <entry key="10002" value="Object-oriented Programming B"/>
                <entry key="10003" value="Operating systems and components."/>
            </map>
        </property>
Copy the code

6, Set injection

<! -- Set insert value tag -->
        <property name="games">
            <set>
              <value>LOL</value>
              <value>CF</value>
              <value>Dream of The Three Kingdoms</value>
            </set>
        </property>
Copy the code

Null injection

<! -- NUll injection -->
        <property name="girlfriends">
            <null></null>
        </property>
Copy the code

Properties injection

<! -- Properties injection -->
        <property name="info">
            <props>
                <prop key="driver">com.mysql.jdbc.Driver</prop>
                <prop key="url">jdbc:mysql://localhost:3306? test</prop>
                <prop key="username">root</prop>
                <prop key="password">123456</prop>
            </props>
        </property>
Copy the code

Testing:

import com.spring.pojo.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/ * * *@ProjectName: Spring5study
 * @Package: PACKAGE_NAME
 * @ClassName: MyTest
 * @Author: Shengrui Zhang *@Date: 2022/2/2 12:57
 * @Version: 1.0 * /
public class MyTest {
    @Test
    public void test1(a){
         ApplicationContext context= new ClassPathXmlApplicationContext("beans.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.toString());
        /* * Student{name=' name ', name=' name ', name=' name ', name=' name ', name=' name ', name=' name ', name=' name ', name=' name ', * books={10001= OBJECT-ORIENTED programming A, 10002= object-oriented programming B, 10003= operating system and principle}, * games=[LOL, CF, dreamthree], * singe ='null', * info={password=123456, url=jdbc:mysql://localhost:3306? test, driver=com.mysql.jdbc.Driver, username=root}} * * */}}Copy the code

Test results:

8.3 Extended injection implementation

User.java [note: there is no parameter constructor!]

package com.spring.pojo;

/ * * *@ProjectName: Spring5study
 * @Package: com.spring.pojo
 * @ClassName: User
 * @Author: Shengrui Zhang *@Date: 2022/2/2 14:04
 * @Version: 1.0 * /
public class User {
    private String name;
    private int age;

    public String getName(a) {
        return name;
    }

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

    public int getAge(a) {
        return age;
    }

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

    @Override
    public String toString(a) {
        return "User{" +
                "name='" + name + '\' ' +
                ", age=" + age +
                '} '; }}Copy the code

1.PNamespace injection: constraint files are required in header files

<! - import restriction: XMLNS: p = "http://www.springframework.org/schema/p" -- >

<! --P(properties: properties) namespace, property still set method -->
<bean id="user" class="com.spring.pojo.User" p:name="Director" p:age="20"/>
Copy the code

2,cNamespace injection: constraint files are required in header files

<! - import restriction: XMLNS: c = "http://www.springframework.org/schema/c" -- >

<! --C(Constructor: Constructor) namespace, attribute still set method -->
<bean id="user2"  class="com.spring.pojo.User" c:name="Director" c:age="21"/>
Copy the code

Found the problem: burst red, just we did not write with reference to the structure!

Solution: add the parameter constructor, here also can see, c is called constructor injection!

Testing:

@Test
public void test02(a) {
    ApplicationContext context = new
        ClassPathXmlApplicationContext("userbeans.xml");
    User user = (User) context.getBean("user");
    System.out.println(user);
}
Copy the code

8.4 Scope of beans

In Spring, the bodies that make up the application and the objects managed by the Spring IoC container are called beans. Simply put, beans are objects that are initialized, assembled, and managed by the IoC container.

category instructions
singleton There is only one instance of a Bean in the Spring loC container, and beans are singletons, default
prototype Each time the Bean is called from the container, a new instance is returned, which is equivalent to executing new XxxBean() each time getBean() is called
request Each HTTP request creates a new Bean, which is scoped only for the WebApplicationContext environment
session The same HTTP Session shares a Bean. Different sessions use different beans. This applies only to WebApplicationContext

The Request, Session, and Application scopes are only used in Web-based applications (regardless of which Web application framework you are using), and only in web-based Spring ApplicationContext.

8.4.1 Singleton

When a bean is scoped to a Singleton, there will be only one shared bean instance in the Spring IoC container, and all requests for the bean will return only the same instance of the bean as long as the ID matches the bean definition. A Singleton is a Singleton type that automatically creates a bean object when the container is created. It exists regardless of whether you use it or not, and the object you get is the same object each time. Note that the Singleton scope is the default scope in Spring. To define a bean as a singleton in XML, you can configure it like this

<! --P(properties: properties) namespace, property still set method -->
<bean id="user" class="com.spring.pojo.User" p:name="Director" p:age="20" scope="singleton"/>
Copy the code

The test class

@Test
public void test02(a) {
    ApplicationContext context = new
        ClassPathXmlApplicationContext("userbeans.xml");
    User user = (User) context.getBean("user");
    User user2 = (User) context.getBean("user");
    System.out.println(user.hashCode());
    System.out.println(user2.hashCode());
    System.out.println(user==user2);
}
Copy the code

8.4.2 Prototype

When a bean is scoped to Prototype, a bean definition corresponds to multiple object instances. A prototype-scoped bean results in a new bean instance being created each time the bean is requested (injected into another bean, or programmatically called on the container’s getBean() method). Prototype is the Prototype type, which is not instantiated when we create the container. Instead, we create an object when we get the bean, and we get a different object each time. As a rule of thumb, you should use the Prototype scope for stateful beans and the Singleton scope for stateless beans. Defining the bean as prototype in XML can be configured as follows:

<! --P(properties: properties) namespace, property still set method -->
<bean id="user" class="com.spring.pojo.User" p:name="Director" p:age="20" scope="prototype"/>
Copy the code

The test class

@Test
public void test02(a) {
    ApplicationContext context = new
        ClassPathXmlApplicationContext("userbeans.xml");
    User user = (User) context.getBean("user");
    User user2 = (User) context.getBean("user");
    System.out.println(user.hashCode());
    System.out.println(user2.hashCode());
    System.out.println(user==user2);
}
Copy the code

8.4.2 Request

When the scope of a bean is Request, it means that in an HTTP Request, one bean definition corresponds to one instance. That is, each HTTP request has its own bean instance, which is created from a bean definition. This scope is valid only in the case of web-based Spring ApplicationContext. Consider the following bean definition:

<bean id="loginAction" class=com.spring.LoginController" scope="request"/>
Copy the code

For each HTTP request, the Spring container creates a new loginController bean instance based on the loginController bean definition, and this loginController Bean instance is valid only within the current HTTP request. So you can safely change the internal state of the instance you build as needed, whereas instances created from the loginController Bean definition in other requests will not see these request-specific state changes. When the processing of the request ends, the request scoped bean instance is destroyed.

8.4.2 Session

When the scope of a bean is Session, it means that in an HTTP Session, one bean definition corresponds to one instance. This scope is valid only in the case of web-based Spring ApplicationContext. Consider the following bean definition:

<bean id="user" class=com.spring.pojo.UserSession" scope="request"/>
Copy the code

For an HTTP Session, the Spring container creates a new UserSession Bean instance based on the UserSession Bean definition, and this UserSession bean is valid only for the current HTTP Session. As with the Request scope, you can safely change the internal state of the instance you create as needed, whereas other HTTP Session instances created under UserSession will not see these session-specific state changes. When an HTTP Session is finally discarded, the beans scoped by that HTTP Session are also discarded.

After the language

The original intention of the director to write blog is very simple, I hope everyone in the process of learning less detours, learn more things, to their own help to leave your praise 👍 or pay attention to ➕ are the biggest support for me, your attention and praise to the director every day more power.

If you don’t understand one part of the article, you can reply to me in the comment section. Let’s discuss, learn and progress together!

Wechat (Z613500) or QQ (1016942589) for detailed communication.