- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) >
- Spring框架設值注入操作的示例分析
這篇文章主要介紹Spring框架設值注入操作的示例分析,文中介紹的非常詳細,具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
一 配置
<?xml version="1.0" encoding="GBK"?> <!-- Spring配置文件的根元素,使用spring-beans-4.0.xsd語(yǔ)義約束 --> <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"> <!-- 配置chinese實(shí)例,其實(shí)現類(lèi)是Chinese類(lèi) --> <bean id="chinese" class="org.crazyit.app.service.impl.Chinese"> <!-- 驅動(dòng)調用chinese的setAxe()方法,將容器中stoneAxe作為傳入參數 --> <property name="axe" ref="stoneAxe"/> </bean> <!-- 配置stoneAxe實(shí)例,其實(shí)現類(lèi)是StoneAxe --> <bean id="stoneAxe" class="org.crazyit.app.service.impl.StoneAxe"/> <!-- 配置steelAxe實(shí)例,其實(shí)現類(lèi)是SteelAxe --> <bean id="steelAxe" class="org.crazyit.app.service.impl.SteelAxe"/> </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)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 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)站