Spring03_DI

本教程源碼請訪問:tutorial_demojava

1、什麼是依賴注入

依賴注入:Dependency Injection ,指容器負責建立和維護對象之間的依賴關係,而不是經過對象自己負責本身的建立和解決本身的依賴。在當前類須要用到其餘類的對象,由Spring爲咱們提供,咱們只須要在配置中說明。git

2、如何進行注入

2.一、構造函數注入

2.1.一、建立項目

  1. 在Idea中新建Maven工程;github

  2. 工程建立完成後添加相應的座標。spring

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>org.codeaction</groupId>
        <artifactId>di</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.2.6.RELEASE</version>
            </dependency>
        </dependencies>
    </project>

2.1.二、添加User類

package org.codeaction.bean;

import java.util.Date;

/**
 * 用戶類
 */
public class User1 {
    private String name;
    private Integer age;
    private String address;
    private Date birthday;

    //有參構造方法
    public User(String name, Integer age, String address, Date birthday) {
        this.name = name;
        this.age = age;
        this.address = address;
        this.birthday = birthday;
    }


    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}

User1類中必定要有有參的構造方法。apache

2.1.三、添加XML配置文件

XML文件在resource目錄下。數組

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="now" class="java.util.Date"></bean>
    <bean id="user1" class="org.codeaction.bean.User1">
        <!-- 經過構造函數注入屬性 -->
        <constructor-arg name="name" value="Tom"></constructor-arg>
        <constructor-arg name="age" value="10"></constructor-arg>
        <constructor-arg name="address" value="上海"></constructor-arg>
        <constructor-arg name="birthday" ref="now"></constructor-arg>
    </bean>
</beans>

構造函數注入使用constructor-arg標籤,這個標籤在bean標籤的內部。maven

constructor-arg標籤中的屬性:ide

  • type:指定要注入的數據的數據類型,該數據類型也是構造函數中某個或某些參數的類型;
  • index:指定要注入的數據給構造函數中指定索引位置的參數賦值。索引的位置是從0開始;
  • name:指定給構造函數中指定名稱的參數賦值;
  • value:提供基本類型和String類型的數據;
  • ref:指定其餘的bean類型數據。它指的就是在spring的Ioc核心容器中出現過的bean對象。

前三個屬性用於指定給構造函數中哪一個參數賦值,其中name屬性最經常使用。函數

2.1.四、添加測試方法

package org.codeaction.test;

import org.codeaction.bean.User1;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        User1 user1 = (User1) context.getBean("user1");
        System.out.println(user1);
    }
}

運行main方法,控制檯輸出以下:測試

User1{name='Tom', age=10, address='上海', birthday=Mon May 25 09:01:58 CST 2020}

2.二、set方法注入

2.2.一、添加User類

package org.codeaction.bean;

import java.util.Date;

public class User2 {
    private String name;
    private Integer age;
    private String address;
    private Date birthday;

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

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

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

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User2{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}

User2類中必定要有set方法。

2.2.二、修改XML配置文件

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="now" class="java.util.Date"></bean>
    <bean id="user1" class="org.codeaction.bean.User1">
        <!-- 經過構造函數注入屬性 -->
        <constructor-arg name="name" value="Tom"></constructor-arg>
        <constructor-arg name="age" value="10"></constructor-arg>
        <constructor-arg name="address" value="上海"></constructor-arg>
        <constructor-arg name="birthday" ref="now"></constructor-arg>
    </bean>
	
    <bean id="user2" class="org.codeaction.bean.User2">
        <!-- 經過set方法注入 -->
        <property name="name" value="Bob"></property>
        <property name="age" value="20"></property>
        <property name="address" value="北京"></property>
        <property name="birthday" ref="now"></property>
    </bean>
</beans>

2.2.三、修改測試方法

package org.codeaction.test;

import org.codeaction.bean.User1;
import org.codeaction.bean.User2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

		//User1 user1 = (User1) context.getBean("user1");
        //System.out.println(user1);

        User2 user2 = (User2) context.getBean("user2");
        System.out.println(user2);
    }
}

運行main方法,控制檯輸出以下:

User2{name='Bob', age=20, address='北京', birthday=Mon May 25 09:37:17 CST 2020}

2.三、注入複雜類型屬性

本質上仍是給屬性注入值,只是被注入的屬性都是複雜類型(數組,List,Set,Map,Properties)。

2.3.一、添加User類

package org.codeaction.bean;

import java.util.*;

public class User3 {
    private String[] hobbies1;
    private List<String> hobbies2;
    private Set<String> hobbies3;
    private Map<String, String> idInfo1;
    private Properties idInfo2;

    public void setHobbies1(String[] hobbies1) {
        this.hobbies1 = hobbies1;
    }

    public void setHobbies2(List<String> hobbies2) {
        this.hobbies2 = hobbies2;
    }

    public void setHobbies3(Set<String> hobbies3) {
        this.hobbies3 = hobbies3;
    }

    public void setIdInfo1(Map<String, String> idInfo1) {
        this.idInfo1 = idInfo1;
    }

    public void setIdInfo2(Properties idInfo2) {
        this.idInfo2 = idInfo2;
    }

    public void show() {
        System.out.println("array----" + Arrays.toString(hobbies1));
        System.out.println("list----" + hobbies2);
        System.out.println("set----" + hobbies3);
        System.out.println("map----" + idInfo1);
        System.out.println("properties----" + idInfo2);
    }
}

2.3.二、修改XML配置文件

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="now" class="java.util.Date"></bean>
    <bean id="user1" class="org.codeaction.bean.User1">
        <!-- 經過構造函數注入屬性 -->
        <constructor-arg name="name" value="Tom"></constructor-arg>
        <constructor-arg name="age" value="10"></constructor-arg>
        <constructor-arg name="address" value="上海"></constructor-arg>
        <constructor-arg name="birthday" ref="now"></constructor-arg>
    </bean>

    <bean id="user2" class="org.codeaction.bean.User2">
        <!-- 經過set方法注入 -->
        <property name="name" value="Bob"></property>
        <property name="age" value="20"></property>
        <property name="address" value="北京"></property>
        <property name="birthday" ref="now"></property>
    </bean>

    <!-- 注入複雜類型屬性 -->
    <bean id="user3" class="org.codeaction.bean.User3">
        <!-- 注入複雜類型屬性 -->
        <property name="hobbies1">
            <array>
                <value>籃球</value>
                <value>讀書</value>
                <value>帆船</value>
            </array>
        </property>
        <property name="hobbies2">
            <list>
                <value>太極</value>
                <value>自由搏擊</value>
                <value>詠春</value>
            </list>
        </property>
        <property name="hobbies3">
            <set>
                <value>旅遊</value>
                <value>蹦極</value>
                <value>馬拉松</value>
            </set>
        </property>
        <property name="idInfo1">
            <map>
                <entry key="name" value="John"></entry>
                <entry key="age">
                    <value>20</value>
                </entry>
                <entry key="gender" value="男"></entry>
            </map>
        </property>
        <property name="idInfo2">
            <props>
                <prop key="address">廣州</prop>
                <prop key="height">180</prop>
            </props>
        </property>
    </bean>
</beans>

用於爲List結構注入的標籤:list、array、set;

用於爲Map結構注入的標籤:map、props;

結構相同,標籤能夠互換。

2.3.三、修改測試方法

package org.codeaction.test;

import org.codeaction.bean.User1;
import org.codeaction.bean.User2;
import org.codeaction.bean.User3;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

        //User1 user1 = (User1) context.getBean("user1");
        //System.out.println(user1);

        //User2 user2 = (User2) context.getBean("user2");
        //System.out.println(user2);

        User3 user3 = (User3)context.getBean("user3");
        user3.show();
    }
}

運行main方法,控制檯輸出以下:

array----[籃球, 讀書, 帆船]
list----[太極, 自由搏擊, 詠春]
set----[旅遊, 蹦極, 馬拉松]
map----{name=John, age=20, gender=男}
properties----{height=180, address=廣州}

2.3.四、修改XML配置文件,互換標籤

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="now" class="java.util.Date"></bean>
    <bean id="user1" class="org.codeaction.bean.User1">
        <!-- 經過構造函數注入屬性 -->
        <constructor-arg name="name" value="Tom"></constructor-arg>
        <constructor-arg name="age" value="10"></constructor-arg>
        <constructor-arg name="address" value="上海"></constructor-arg>
        <constructor-arg name="birthday" ref="now"></constructor-arg>
    </bean>

    <bean id="user2" class="org.codeaction.bean.User2">
        <!-- 經過set方法注入 -->
        <property name="name" value="Bob"></property>
        <property name="age" value="20"></property>
        <property name="address" value="北京"></property>
        <property name="birthday" ref="now"></property>
    </bean>

    <!-- 注入複雜類型屬性 -->
    <bean id="user3" class="org.codeaction.bean.User3">
        <!-- 注入複雜類型屬性 -->
        <property name="hobbies1">
            <set>
                <value>旅遊</value>
                <value>蹦極</value>
                <value>馬拉松</value>
            </set>            
        </property>
        <property name="hobbies2">
            <array>
                <value>籃球</value>
                <value>讀書</value>
                <value>帆船</value>
            </array>
        </property>
        <property name="hobbies3">
            <list>
                <value>太極</value>
                <value>自由搏擊</value>
                <value>詠春</value>
            </list>
        </property>
        <property name="idInfo1">
            <props>
                <prop key="address">廣州</prop>
                <prop key="height">180</prop>
            </props>
        </property>
        <property name="idInfo2">
            <map>
                <entry key="name" value="John"></entry>
                <entry key="age">
                    <value>20</value>
                </entry>
                <entry key="gender" value="男"></entry>
            </map>
        </property>
    </bean>
</beans>

運行main方法,控制檯輸出以下:

array----[旅遊, 蹦極, 馬拉松]
list----[籃球, 讀書, 帆船]
set----[太極, 自由搏擊, 詠春]
map----{height=180, address=廣州}
properties----{age=20, name=John, gender=男}

經過上面的修改,說明標籤結構相同,標籤能夠互換。

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息