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會默認(rèn)創(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. Android table布局開發(fā)實(shí)現(xiàn)簡單計(jì)算器2. 理解PHP5中static和const關(guān)鍵字3. jQuery 實(shí)現(xiàn)DOM元素拖拽交換位置的實(shí)例代碼4. php模擬實(shí)現(xiàn)斗地主發(fā)牌5. IntelliJ IDEA安裝插件的方法步驟6. phpstorm恢復(fù)默認(rèn)設(shè)置的方法步驟7. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. Python random庫使用方法及異常處理方案9. Vuex localStorage的具體使用10. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟

網(wǎng)公網(wǎng)安備