您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關(guān)如何在Spring中定義抽象Bean和子Bean,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
一 配置
<?xml version="1.0" encoding="GBK"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <!-- 定義Axe實例 --> <bean id="steelAxe" class="org.crazyit.app.service.impl.SteelAxe"/> <!-- 指定abstract="true"定義抽象Bean --> <bean id="personTemplate" abstract="true"> <property name="name" value="crazyit"/> <property name="axe" ref="steelAxe"/> </bean> <!-- 通過指定parent屬性指定下面Bean配置可從父Bean繼承得到配置信息 --> <bean id="chinese" class="org.crazyit.app.service.impl.Chinese" parent="personTemplate"/> <bean id="american" class="org.crazyit.app.service.impl.American" parent="personTemplate"/> </beans>
二 接口
Axe
package org.crazyit.app.service; public interface Axe { public String chop(); }
Person
package org.crazyit.app.service; public interface Person { public void useAxe(); }
三 實現(xiàn)類
1 American
package org.crazyit.app.service.impl; import org.crazyit.app.service.*; public class American implements Person { private Axe axe; private String name; public void setAxe(Axe axe) { System.out.println("Spring執(zhí)行依賴關(guān)系注入..."); this.axe = axe; } public void setName(String name) { this.name = name; } public void useAxe() { System.out.println("我是美國人:名字為:" + name + "。正在用斧頭" + axe.chop()); } }
2 Chinese
package org.crazyit.app.service.impl; import org.crazyit.app.service.*; public class Chinese implements Person { private Axe axe; private String name; public void setAxe(Axe axe) { System.out.println("Spring執(zhí)行依賴關(guān)系注入..."); this.axe = axe; } public void setName(String name) { this.name = name; } public void useAxe() { System.out.println("我是中國人:名字為:" + name + "。正在用斧頭" + axe.chop()); } }
3 SteelAxe
package org.crazyit.app.service.impl; import org.crazyit.app.service.*; public class SteelAxe implements Axe { public String chop() { return "鋼斧砍柴真快"; } }
4 StoneAxe
package org.crazyit.app.service.impl; import org.crazyit.app.service.*; public class StoneAxe implements Axe { public String chop() { return "石斧砍柴好慢"; } }
四 測試類
package lee; import org.springframework.context.ApplicationContext; import org.springframework.context.support.*; import org.crazyit.app.service.*; public class BeanTest { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); } }
關(guān)于如何在Spring中定義抽象Bean和子Bean就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。