[5] Dependency Injection DI (Dependency Injection)

6, dependency injection

concept

  • Dependency Injection (DI).
  • Dependency: Bean object creation depends on the container. Bean object's dependent resources.
  • Injection: Refers to the resource on which the Bean object depends, which is set and assembled by the container.

Constructor injection

I have talked about it before

Set injection (emphasis)

The property required to be injected must have a set method. The method name of the set method is capitalized by set + property. If the property is of boolean type and there is no set method, it is is.

Test pojo class:

Address.java

package com.kuber.pojo;

public class Address {
    
    

    private String homeAddress;

    public String getHomeAddress() {
    
    
        return homeAddress;
    }

    public void setHomeAddress(String homeAddress) {
    
    
        this.homeAddress = homeAddress;
    }

    @Override
    public String toString() {
    
    
        return "Address{" +
                "homeAddress='" + homeAddress + '\'' +
                '}';
    }
}

Student.java:

package com.kuber.pojo;



import java.util.*;

public class Student {
    
    
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbies;
    private Map<String,String> card;
    private Set<String> games;
    private String girlfriend;
    private Properties info;

    public String getGirlfriend() {
    
    
        return girlfriend;
    }

    public void setGirlfriend(String girlfriend) {
    
    
        this.girlfriend = girlfriend;
    }

    public String getName() {
    
    
        return name;
    }

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

    public Address getAddress() {
    
    
        return address;
    }

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

    public String[] getBooks() {
    
    
        return books;
    }

    public void setBooks(String[] books) {
    
    
        this.books = books;
    }

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

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

    public Map<String, String> getCard() {
    
    
        return card;
    }

    public void setCard(Map<String, String> card) {
    
    
        this.card = card;
    }

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

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

    public Properties getInfo() {
    
    
        return info;
    }

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

    @Override
    public String toString() {
    
    
        return "Student{" +
                "name='" + name + '\'' +
                ", address=" + address.toString() +
                ", books=" + Arrays.toString(books) +
                ", hobbies=" + hobbies +
                ", card=" + card +
                ", games=" + games +
                ", info=" + info +
                '}';
    }
}

Various attributes of student are injected into beans.xml, one by one comparison:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <import resource="userbeans.xml"/>
    <import resource="employee-beans.xml"/>

    <bean id="address" class="com.kuber.pojo.Address">
        <property name="homeAddress" value="河南"/>
    </bean>
    
    <!--Bean注入,注意点:这里的值是一个引用,ref-->
    <bean id="student" class="com.kuber.pojo.Student">
        <property name="name" value="倪文翰"/>
        <property name="address" ref="address"/>
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>三国演义</value>
                <value>水浒传</value>
                <value>西游记</value>
            </array>
        </property>
        <property name="hobbies">
            <list>
                <value>敲代码</value>
                <value>看书</value>
                <value>打游戏</value>
            </list>
        </property>
        <property name="card">
            <map>
                <entry key="身份证" value="46541651"/>
                <entry key="学生证" value="201619823"/>
            </map>
        </property>
        <property name="games">
            <set>
                <value>GTA5</value>
                <value>LOL</value>
                <value>CS:GO</value>
            </set>
        </property>
        <property name="girlfriend" value="gyy"/>
        <property name="info">
            <props>
                <prop key="username">root</prop>
                <prop key="password">root</prop>
                <prop key="driver">dddd</prop>
                <prop key="url">aqwer</prop>
            </props>
        </property>
    </bean>
</beans>

Test code:

@Test
public void test1(){
    
    
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    Student student = (Student) context.getBean("student");
    System.out.println(student);
    /*Student{
         name='倪文翰',
         address=Address{homeAddress='河南'},
         books=[红楼梦, 三国演义, 水浒传, 西游记],
         hobbies=[敲代码, 看书, 打游戏],
         card={身份证=46541651, 学生证=201619823},
         games=[GTA5, LOL, CS:GO],
         info={password=root, url=aqwer, driver=dddd, username=root}
     }

     */
}

Test Results:

Insert picture description here

p naming and c naming injection

User.java: [Note: There is no parameter constructor here!

 public class User {
    
    
     private String name;
     private int age;
 
     public void setName(String name) {
    
    
         this.name = name;
    }
 
     public void setAge(int age) {
    
    
         this.age = age;
    }
 
     @Override
     public String toString() {
    
    
         return "User{" +
                 "name='" + name + '\'' +
                 ", age=" + age +
                 '}';
    }
 }

P namespace injection: Need to add constraint files in the header file

c Namespace injection: Need to add constraint files in the header 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"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="user" class="com.kuber.pojo.User" p:username="工藤静香" p:age="20"/>
    <bean id="user2" class="com.kuber.pojo.User" c:username="工藤胖虎" c:age="40" scope="singleton"/>
    <!--默认单例模式,scope=singleton""-->
</beans>

Found the problem: It's popular, we didn't write a parameter structure just now!

Solution: Add the parameterized constructor, you can also know here, c is the so-called constructor injection!

Test code:

@Test
public void test2(){
    
    
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    User user = context.getBean("user", User.class);
    System.out.println(user);
}

[Insert picture description here

Bean scope

In Spring, the main body of the application and the objects managed by the Spring IoC container are called beans. Simply put, a bean is an object initialized, assembled and managed by the IoC container.

Insert picture description here

Among several scopes, request and session scopes are only used in web-based applications (don’t care what web application framework you are using), and can only be used in web-based Spring ApplicationContext environments.

  • Singleton

    When the scope of a bean is Singleton, there will only be one shared bean instance in the Spring IoC container, and all requests to the bean, as long as the id matches the bean definition, will only return the same instance of the bean. Singleton is a singleton type, that is, when the container is created, a bean object is automatically created at the same time. No matter whether you use it or not, it exists, and the object obtained every time is the same object. 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:

     <bean id="ServiceImpl" class="cn.csdn.service.ServiceImpl" scope="singleton">
    
  • Prototype

    When the scope of a bean is Prototype, it means that a bean definition corresponds to multiple object instances. Prototype scoped beans will cause a new bean instance to be created every time the bean is requested (injected into another bean, or the container's getBean() method is called programmatically). Prototype is a prototype type. It is not instantiated when we create the container. Instead, an object is created when we get the bean, and the object we get is not the same object every time. According to experience, prototype scope should be used for stateful beans, and singleton scope should be used for stateless beans. Define the bean as a prototype in XML, which can be configured like this:

     <bean id="account" class="com.foo.DefaultAccount" scope="prototype"/>  
      或者
     <bean id="account" class="com.foo.DefaultAccount" singleton="false"/>
    
  • Request

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

     <bean id="loginAction" class=cn.csdn.LoginAction" scope="request"/>
    

    For each HTTP request, the Spring container will create a brand new LoginAction bean instance based on the definition of loginAction bean, and the loginAction bean instance is only valid in the current HTTP request, so you can safely change the internal state of the created instance as needed. In other requests, instances created according to the loginAction bean definition will not see these state changes specific to a certain request. When processing the request ends, the bean instance in the request scope will be destroyed.

  • Session

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

     <bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>
    

    For a certain HTTP Session, the Spring container will create a brand new userPreferences bean instance based on the userPreferences bean definition, and the userPreferences bean is only valid in the current HTTP Session. As with the request scope, you can safely change the internal state of the created instance as needed, and other HTTP Sessions created based on userPreferences will not see these state changes specific to an HTTP Session. When the HTTP Session is finally discarded, the beans in the scope of the HTTP Session will also be discarded.

Guess you like

Origin blog.csdn.net/weixin_43215322/article/details/110353261