接上篇 spring依賴注入1 spring依賴注入之xml注入方式
本篇主要講解基於註解的注入 。
在此之前,大家可以先看一下我寫的自動注入有點印象,下文講解的時候會用到
spring之自動注入
使用註解注入屬性,我們就不需要在xml中進行配置了。
主要工作有兩步,1.在類中加入註解。2.在xml總宣告掃瞄器
我們先對簡單屬性進行賦值,還是熟悉的學生和學校類,
student類
import org.springframework.beans.factory.annotation.value;
import org.springframework.stereotype.component;
@component("studnet")
public class student
public void setname(string name)
public void setage(int age)
@override
public string tostring() ';}}
這裡介紹component註解標籤
@component 相當於bean 建立類的物件,預設單例
*其中的value 就是bean的id 註解中屬性是value 可以隱去不寫,而如果你沒有設定,則預設是類名的小寫
*在xml檔案中進行配置,宣告元件掃瞄器,宣告掃瞄包所在的位置。
@value 是給屬性賦值的註解,有兩種方式,一種在屬性名上直接賦值,一種是在setter方法上面賦值
@value("tom")
public void setname(string name)
@value("18")
public void setage(int age)
執行測試類
兩種方法一摸一樣!
接下來我們對引用型別進行賦值
引用型別主要是使用自動注入的方式
使用@autowired
在引用型別的屬性名上使用,該註解預設是使用bytype的自動注入方式,當掃瞄器掃瞄到這裡時,會自動按照引用型別的資料型別進行查詢,找到school型別進行賦值
school類
import org.springframework.beans.factory.annotation.value;
import org.springframework.stereotype.component;
@component("school")
public class school
public void setname(string name)
public void setaddress(string address)
@override
public string tostring() ';}}
student型別中新增@autowired
@component(value ="student")
public class student {
private string name;
private int age;
@autowired
private school school;
執行測試類
我們還可以使用byname的注入方式
在@autowired下面使用 @qualifier(「school」)
這樣就可以使用按name的方法進行自動注入!
@autowired
@qualifier("school")
private school school;
執行結果和上邊是一摸一樣的,就不貼了哈。
同時,還有乙個@resource註解,和@autowired差不多,只是預設使用byname注入,如果失敗,再使用bytype,這個等下次有時間再說哈。
spring 依賴注入 Spring依賴注入
依賴注入 dependency injection,簡稱di 與控制反轉 ioc 的含義相同控制反 在使用spring框架之後,物件的例項不再由呼叫者來建立,而是由spring容器來建立,spring容器會負責控制程式之間的關係,而不是由呼叫者的程式 直接控制,這樣控制權由應用程式轉移到了sprin...
Spring 2 依賴注入
依賴 a對於像依賴b物件的方法 核心機制 控制反轉 ioc 別名 依賴注入 程式無需主動獲取被依賴的物件,只等spring容器注入。property子元素和對應的setter方法 依賴注入的兩種方式 設值注入 ioc容器使用成員變數的setter方法注入被依賴的物件。構造注入 ioc容器使用構造器注...
Spring依賴注入相關筆記
1.概述 從spring2.5開始就可以使用註解來配置依賴注入。而不是採用xml來描述乙個bean連線,你可以使用相關類,方法或字段宣告的註解,將bean配置移動到元件類本身。在xml注入之前進行註解注入,因此後者的配置將通過兩種方式的屬性連線別前者重寫。註解連線在預設的情況下在spring容器中打...