這篇文章將為大家詳細講解有關如何在Spring中定義抽象Bean和子Bean,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
一 配置
<?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(); }
三 實現類
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執行依賴關系注入..."); 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執行依賴關系注入..."); 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"); } }
關于如何在Spring中定義抽象Bean和子Bean就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。