日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring自动装配Bean

發布時間:2025/3/12 javascript 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring自动装配Bean 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

除了使用 XML 和 Annotation 的方式裝配 Bean 以外,還有一種常用的裝配方式——自動裝配。自動裝配就是指 Spring 容器可以自動裝配(autowire)相互協作的 Bean 之間的關聯關系,將一個 Bean 注入其他 Bean 的 Property 中。

要使用自動裝配,就需要配置 元素的 autowire 屬性。autowire 屬性有五個值。

autowire 的屬性和作用

名稱說明
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"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><bean id="personDao" class="com.mengma.annotation.PersonDaoImpl" /><bean id="personService" class="com.mengma.annotation.PersonServiceImpl"autowire="byName" /><bean id="personAction" class="com.mengma.annotation.PersonAction"autowire="byName" /> </beans>

在上述配置文件中,用于配置 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。