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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

香辣弹簧:自动接线的不同方法

發布時間:2023/12/3 编程问答 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 香辣弹簧:自动接线的不同方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

我想展示使用Spring的@Autowired批注的不同方式: ConstructorMethodField自動裝配。 我展示的示例都是byType自動裝配模式的一種形式( constructor自動裝配模式類似于byType )。 請參閱Spring Reference指南 ,以獲取有關自動裝配模式的更多信息。

構造器自動裝配

使用從屬bean作為構造函數參數創建一個構造函數,并將@Autowired批注添加到該構造函數。 構造函數自動裝配的一個很大的好處是,該字段可以定為最終字段,因此構造后不得更改。

package com.jdriven;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;@Component public class AutowiredCapabilityBean {//The InjectableBean can be made finalprivate final InjectableBean injectableBean; //The InjectableBean is autowired byType and is required.//An error is thrown when no bean or multiple beans of InjectableBean exist@Autowiredpublic AutowiredCapabilityBean(InjectableBean injectableBean) {this.injectableBean = injectableBean;} }

方法自動裝配

為從屬bean創建一個setter方法,并將@Autowired批注添加到setter方法。 使用方法自動裝配的一個缺點是可以在生產代碼中調用setter,從而意外覆蓋了bean。

package com.jdriven;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;@Component public class AutowiredCapabilityBean {private InjectableBean injectableBean; //No explicit constructor is needed. The default constructor is used.//The InjectableBean is autowired byType, but is not required.@Autowiredpublic void setInjectableBean(InjectableBean injectableBean) {this.injectableBean = injectableBean;} }

現場自動接線

為從屬bean創建一個字段(成員變量),并將@Autowired批注添加到該字段。 這種自動裝配方式的代碼更少,但是需要使用InjectableBean的實現來測試AutowiredCapabilityBean ,因為它沒有構造函數,也沒有設置方法。

package com.jdriven;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component;@Component public class AutowiredCapabilityBean {//The InjectableBean is autowired byType and is required.@Autowiredprivate InjectableBean injectableBean; //No explicit constructor is needed. The default constructor is used. }

翻譯自: https://www.javacodegeeks.com/2015/03/spicy-spring-different-ways-of-autowiring.html

總結

以上是生活随笔為你收集整理的香辣弹簧:自动接线的不同方法的全部內容,希望文章能夠幫你解決所遇到的問題。

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