- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) > 編程語(yǔ)言 >
- Spring中怎么實(shí)現注入嵌套Bean操作
這篇文章給大家介紹Spring中怎么實(shí)現注入嵌套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"> <bean id="chinese" class="org.crazyit.app.service.impl.Chinese"> <!-- 驅動(dòng)調用chinese的setAxe()方法,使用嵌套Bean作為參數 --> <property name="axe"> <!-- 嵌套Bean配置的對象僅作為setter方法的參數 嵌套Bean不能被容器訪(fǎng)問(wèn),因此無(wú)需指定id屬性--> <bean class="org.crazyit.app.service.impl.SteelAxe"/> </property> </bean></beans>
二 接口
Axe
package org.crazyit.app.service;public interface Axe{ // Axe接口里有個(gè)砍的方法 public String chop();}
Person
package org.crazyit.app.service;public interface Person{ // 定義一個(gè)使用斧子的方法 public void useAxe();}
三 實(shí)現
Chinese
package org.crazyit.app.service.impl;import org.crazyit.app.service.*;public class Chinese implements Person{ private Axe axe; // 設值注入所需的setter方法 public void setAxe(Axe axe) { this.axe = axe; } // 實(shí)現Person接口的useAxe方法 public void useAxe() { // 調用axe的chop()方法, // 表明Person對象依賴(lài)于axe對象 System.out.println(axe.chop()); }}
StoneAxe
package org.crazyit.app.service.impl;import org.crazyit.app.service.*;public class StoneAxe implements Axe{ public String chop() { return "石斧砍柴好慢"; }}
SteelAxe
package org.crazyit.app.service.impl;import org.crazyit.app.service.*;public class SteelAxe implements Axe{ public String chop() { return "鋼斧砍柴真快"; }}
四 測試類(lèi)
package lee;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.crazyit.app.service.*;public class BeanTest{ public static void main(String[] args)throws Exception { // 創(chuàng )建Spring容器 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // 獲取chinese 實(shí)例 Person p = ctx.getBean("chinese" , Person.class); // 調用useAxe()方法 p.useAxe(); }}
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。
Copyright ? 2009-2022 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 特網(wǎng)科技 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 百度云 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站