Spring Bean常用依賴注入方式詳解
一般而言,Spring的依賴注入有三種:構(gòu)造器注入、setter注入以及接口注入。本文主要講構(gòu)造器注入與setter注入。
1、構(gòu)造器注入
為了讓Spring完成構(gòu)造器注入,我們需要去描述具體的類、構(gòu)造方法并設(shè)置構(gòu)造方法的對應(yīng)參數(shù)。
代碼如下:
public class Role { private Long id; private String roleName; private String note; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public Role(String roleName, String note) { this.roleName = roleName; this.note = note; } public Role() { } public void run() { System.out.println('roleName:' + roleName + ';' + 'note:' + note); }}
這個時候是沒有辦法利用無參的構(gòu)造方法去創(chuàng)建對象的,為了使Spring能正確創(chuàng)建這個對象,需要在xml文件中加入如下bean:
<bean class='com.ssm.chapter.pojo.Role'> <constructor-arg index='0' value='總經(jīng)理' /> <constructor-arg index='1' value='公司管理者' /> </bean>
其中,constructor-arg元素用于定義類構(gòu)造方法的參數(shù),index用于定義參數(shù)的位置,而value是設(shè)置值,通過這樣定義spring便知道使用Role(String, String)這樣的構(gòu)造方法去創(chuàng)建對象了。
2、使用setter注入
setter注入是Spring最主流的注入方式,它消除了使用構(gòu)造器注入多個參數(shù)的可能性,可以把構(gòu)造參數(shù)聲明為無參的,然后使用setter注入為其設(shè)置對應(yīng)的值。需要注意的是,如果類中沒有構(gòu)造函數(shù),JVM會默認創(chuàng)建一個無參構(gòu)造函數(shù)。xml代碼清單如下:
<bean > <property name='roleName' value='高級工程師' /> <property name='note' value='重要人員' /> </bean>
接著編寫測試類即可:
ApplicationContext ctx = new ClassPathXmlApplicationContext('spring-cfg.xml');Role role = (Role) ctx.getBean('role2');role.run();
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP中if語句、select 、while循環(huán)的使用方法2. xml中的空格之完全解說3. ASP中解決“對象關(guān)閉時,不允許操作。”的詭異問題……4. ASP動態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗分享5. msxml3.dll 錯誤 800c0019 系統(tǒng)錯誤:-2146697191解決方法6. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁7. XML入門的常見問題(四)8. html小技巧之td,div標(biāo)簽里內(nèi)容不換行9. 解決ASP中http狀態(tài)跳轉(zhuǎn)返回錯誤頁的問題10. WMLScript的語法基礎(chǔ)
