日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

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

發(fā)布時(shí)間:2023/12/3 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 香辣弹簧:不同的自动接线方式 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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

構(gòu)造器自動(dòng)裝配

使用從屬bean作為構(gòu)造函數(shù)參數(shù)創(chuàng)建一個(gè)構(gòu)造函數(shù),并將@Autowired批注添加到該構(gòu)造函數(shù)。 構(gòu)造函數(shù)自動(dòng)裝配的一大優(yōu)點(diǎn)是可以將字段定為最終字段,因此構(gòu)造后不得更改。

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;} }

方法自動(dòng)裝配

為從屬bean創(chuàng)建一個(gè)setter方法,并將@Autowired批注添加到setter方法。 使用方法自動(dòng)裝配的一個(gè)缺點(diǎn)是可以在生產(chǎn)代碼中調(diào)用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;} }

現(xiàn)場(chǎng)自動(dòng)接線(xiàn)

為從屬bean創(chuàng)建一個(gè)字段(成員變量),并將@Autowired批注添加到該字段。 這種自動(dòng)裝配方式的代碼更少,但是需要使用InjectableBean的實(shí)現(xiàn)來(lái)測(cè)試AutowiredCapabilityBean ,因?yàn)樗鼪](méi)有構(gòu)造函數(shù),也沒(méi)有設(shè)置方法。

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

總結(jié)

以上是生活随笔為你收集整理的香辣弹簧:不同的自动接线方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。