Spring黑馬:依賴注入(Dependency Injection)


1.IOC的作用:降低程序之間的耦合(依賴關係)
2.依賴關係的管理:以後都交給spring來維護。
在當前類需要用到其他類的對象,由spring來提供,我們只需要在配置文件中說明依賴關係的維護,稱爲依賴注入。
3.依賴注入:
能注入的數據有3類:基本類型和Spring;其他bean類型(在配置文件中或者註解配置過的bean); 複雜類型/集合類型
注入的方式有3種:(1)使用構造函數提供;(2)使用set方法提供;(3)使用註解提供


1.依賴注入的3種方式(獲取bean對象)

1.1 構造函數注入

使用的標籤:constructor-arg
標籤出現的位置:bean標籤的內部
標籤中的屬性:

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

優勢:在獲取bean對象時,注入數據是必須的操作,否則對象無法創建成功。
弊端:改變了bean對象的實例化方式,使我們在創建對象時,如果用不到這些數據,也必須提供。
在這裏插入圖片描述

 <bean id="accountService" class="com.jh.service.impl.AccountServiceImpl">
        <constructor-arg name="name" value="張三"></constructor-arg>
        <constructor-arg name="age" value="23"></constructor-arg>
        <constructor-arg name="birthday" ref="date"></constructor-arg>
 </bean>
    
    <!--配置一個日期對象-->
    <bean id="date" class="java.util.Date"></bean>      

1.2 使用set方法注入

涉及的標籤:property,出現的位置在 bean標籤的內部
標籤屬性:

  • name: 用於指定注入時所調用的set方法名稱
  • value:用於提供基本類型和String類型的數據
  • ref :用於指定其他的bean類型數據。它指的就是在spring的Ioc核心容器中出現過的bean對象

優勢:創建對象沒有明確的限制,可以直接使用默認構造函數
弊端:如果有某個成員必須有值,則獲取對象是有可能set方法沒有執行。
在這裏插入圖片描述

 <bean id="accountService2" class="com.jh.service.impl.AccountServiceImpl2">
        <property name="name" value="李四"></property>
        <property name="age" value="21"></property>
        <property name="birthday" ref="date"></property>
    </bean>
   
    <!--配置一個日期對象-->
    <bean id="date" class="java.util.Date"></bean> 

1.3 註解注入

用於創建bean對象的註解


2. 依賴注入的3類數據(其實就是設定參數值)

在依賴注入的3種方式中都有數據的注入
(1) 基本類型和Spring的注入
在這裏插入圖片描述
(2)其他bean類型(在配置文件中或者註解配置過的bean)的注入
在這裏插入圖片描述
(3) 複雜類型的注入/集合類型的注入
用於給List結構集合注入的標籤: list,array,set
用於給Map結構集合注入的標籤: map props
結構相同,標籤可以互換
在這裏插入圖片描述

<bean id="accountService3" class="com.jh.service.impl.AccountServiceImpl3">
        <property name="myStrs">
            <array>
                <value>胡歌</value>
                <value>胡天</value>
                <value>沙溢</value>
            </array>
        </property>
        <property name="myList">
            <list>
                <value>小狗</value>
                <value>小貓</value>
                <value>老鼠</value>
            </list>
        </property>
        <property name="mySet">
            <set>
                <value>玫瑰</value>
                <value>菊花</value>
                <value>康乃馨</value>
            </set>
        </property>
        <property name="myMap">
            <map>
                <entry key="a" value="蘋果"></entry>
                <entry key="b">
                    <value>香蕉</value>
                </entry>
            </map>
        </property>
        <property name="myProps">
            <props>
                <prop key="1">ccc</prop>
                <prop key="2">dd</prop>
            </props>
        </property>
    </bean>

3. 案例

bean.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
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--(1)構造函數注入:-->
    <bean id="accountService" class="com.jh.service.impl.AccountServiceImpl">
        <constructor-arg name="name" value="張三"></constructor-arg>
        <constructor-arg name="age" value="23"></constructor-arg>
        <constructor-arg name="birthday" ref="date"></constructor-arg>
    </bean>
    <!--配置一個日期對象-->
    <bean id="date" class="java.util.Date"></bean>

    <!--(2)使用set方法注入:-->
    <bean id="accountService2" class="com.jh.service.impl.AccountServiceImpl2">
        <property name="name" value="李四"></property>
        <property name="age" value="21"></property>
        <property name="birthday" ref="date"></property>
    </bean>

    <!--複雜類型的注入/集合類型的注入-->
    <bean id="accountService3" class="com.jh.service.impl.AccountServiceImpl3">
        <property name="myStrs">
            <array>
                <value>胡歌</value>
                <value>胡天</value>
                <value>沙溢</value>
            </array>
        </property>
        <property name="myList">
            <list>
                <value>小狗</value>
                <value>小貓</value>
                <value>老鼠</value>
            </list>
        </property>
        <property name="mySet">
            <set>
                <value>玫瑰</value>
                <value>菊花</value>
                <value>康乃馨</value>
            </set>
        </property>
        <property name="myMap">
            <map>
                <entry key="a" value="蘋果"></entry>
                <entry key="b">
                    <value>香蕉</value>
                </entry>
            </map>
        </property>
        <property name="myProps">
            <props>
                <prop key="1">ccc</prop>
                <prop key="2">dd</prop>
            </props>
        </property>
    </bean>
</beans>

com\jh\service業務層接口

package com.jh.service;
public interface IAccountService {
    void saveAccount();
}

com\jh\service\impl業務層3個實現類

(1)構造函數注入:AccountServiceImpl

package com.jh.service.impl;
import com.jh.service.IAccountService;
import java.util.Date;
public class AccountServiceImpl implements IAccountService {
    //如果是經常變化的數據,並不適用於注入的方式
    private String name;
    private Integer age;
    private Date birthday;
    public AccountServiceImpl(String name, Integer age, Date birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }
    public void  saveAccount(){
        System.out.println("AccountServiceImpl執行了"+name+","+age+","+birthday);
    }
}

(2)使用set方法注入:AccountServiceImpl2

package com.jh.service.impl;
import com.jh.service.IAccountService;
import java.util.Date;
public class AccountServiceImpl2 implements IAccountService {
    //如果是經常變化的數據,並不適用於注入的方式
    private String name;
    private Integer age;
    private Date birthday;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public Date getBirthday() {
        return birthday;
    }

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

    public void  saveAccount(){
        System.out.println("AccountServiceImpl2執行了"+name+","+age+","+birthday);
    }
}

注入複雜類型/集合類型 數據:AccountServiceImpl3

package com.jh.service.impl;
import com.jh.service.IAccountService;
import java.util.*;
public class AccountServiceImpl3 implements IAccountService {
    private String[] myStrs;
    private List<String> myList;
    private Set<String> mySet;
    private Map<String,String> myMap;
    private Properties myProps;

    public String[] getMyStrs() {
        return myStrs;
    }

    public void setMyStrs(String[] myStrs) {
        this.myStrs = myStrs;
    }

    public List<String> getMyList() {
        return myList;
    }

    public void setMyList(List<String> myList) {
        this.myList = myList;
    }

    public Set<String> getMySet() {
        return mySet;
    }

    public void setMySet(Set<String> mySet) {
        this.mySet = mySet;
    }

    public Map<String, String> getMyMap() {
        return myMap;
    }

    public void setMyMap(Map<String, String> myMap) {
        this.myMap = myMap;
    }

    public Properties getMyProps() {
        return myProps;
    }

    public void setMyProps(Properties myProps) {
        this.myProps = myProps;
    }

    public void  saveAccount(){
        //數組需要用 Arrays
        System.out.println(Arrays.toString(myStrs));
        System.out.println(myList);
        System.out.println(mySet);
        System.out.println(myMap);
        System.out.println(myProps);
    }
}

Client.java

package com.jh.ui;
import com.jh.service.IAccountService;
import com.jh.service.impl.AccountServiceImpl;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Client {

    public static void main(String[] args) {
        //--------ApplicationContext 立即加載----------------------
        //1.獲取核心容器對象
        ApplicationContext ac= new ClassPathXmlApplicationContext("bean.xml");
        //2.根據id獲取Bean對象
        //(1)構造函數注入
        IAccountService as= (IAccountService)ac.getBean("accountService");
        as.saveAccount();//AccountServiceImpl執行了張三,23,Sat Feb 15 17:13:06 CST 2020

        //(2)使用set方法注入
        IAccountService as2= (IAccountService)ac.getBean("accountService2");
        as2.saveAccount();//AccountServiceImpl2執行了李四,21,Sat Feb 15 17:44:31 CST 2020

        //使用set方法注入 複雜類型/集合類型 數據
        IAccountService as3= (IAccountService)ac.getBean("accountService3");
        as3.saveAccount();//
        }
    }
發佈了95 篇原創文章 · 獲贊 15 · 訪問量 6102
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章