香辣弹簧:自动接线的不同方法
生活随笔
收集整理的這篇文章主要介紹了
香辣弹簧:自动接线的不同方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我想展示使用Spring的@Autowired批注的不同方式: Constructor , Method和Field自動裝配。 我展示的示例都是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
總結
以上是生活随笔為你收集整理的香辣弹簧:自动接线的不同方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 甲片是什么 何谓甲片
- 下一篇: InetAddressImpl#look