Spring自動裝配Bean實現過程詳解

2022-10-05 03:12:12 字數 1143 閱讀 3979

要使用自動裝配,就需要配置 元素的 autowire 屬性。autowire 屬性有五個值,具體說明如表 1 所示。

表 1 autowire 的屬性和作用

名稱www.cppcns.com 說明

byname

根據 property 的 name 自動裝配,如果乙個 bean 的 name 和另乙個 bean 中的 property 的 name 相同,則自動裝配這個 bean 到 property 中。

bytype

根據 property 的資料型別(type)自動裝配,如果乙個 bean 的資料型別相容另乙個 bean 中 property 的資料型別,則自動裝配。

constructor

根據構造方法的引數的資料型別,進行 bytype 模式的自動裝配。

autodetect

如果發現預設的構造方法,則用 constructor 模式,否則用 bytype 模式。

no預設情況下,不使用自動裝配,bean 依賴必須通過 ref 元素定義。

下面通過案例演示如何實現自動裝配。首先將 applicationcontext.xml 配置檔案修改成自動裝配形式,如下所示。

<?xml version="1.0" encoding="utf-8"?>

ldwcmd

/spring-context.xsd">

在上述配置檔案中,用於配置 personservice 和 personaction 的 元素中除了 id 和 class 屬性以外,還程式設計客棧增加了 autowire 屬性,並將其屬性值設定為 byname(按屬性名稱自動裝配)。

預設情況下,配置檔案中需要通過 ref 裝配 bean,但設定了 autowire="byname",spring 會在配置檔案中自動尋找與屬性名字 persondao 相同的 ,找到後,通過呼叫 setpersondao(persondao persondao)方法將 id 為 persondao 的 bean 注入 id 為 personservice 的 bean 中,這時就不需要通過 ref 裝配了。

使用 junit 再次執行測試類中的 test() 方法,控制台的顯示結果如圖所示。

本文標題: spring自動裝配bean實現過程詳解

本文位址: /ruanjian/j**a/301208.html

spring 自動裝配bean

在spring中,支援 5 自動裝配模式。public class customer public void setperson person person 要啟用 autowired,必須註冊 autowiredannotationbeanpostprocessor 可以使用在 set方法 構造方...

(Spring)自動裝配bean

自動裝配說明 spring的自動裝配需要從兩個角度來實現,或者說是兩個操作 元件掃瞄和自動裝配組合發揮巨大威力,使得顯示的配置降低到最少。public class cat public class dog public class people public void setcat cat cat ...

Spring自動裝配bean

configuration顯示這是乙個配置類,componentscan無其他配置則預設在該類所在包內開啟元件掃瞄,若有多個包則寫成 componentscan basepackages 若有多個類,則 componentscan basepackagesclasses package sounds...