您好,登錄后才能下訂單哦!
本文實(shí)例講述了Spring使用@Resource配置依賴操作。分享給大家供大家參考,具體如下:
一 配置
<?xml version="1.0" encoding="GBK"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 自動(dòng)掃描指定包及其子包下的所有Bean類 --> <context:component-scan base-package="org.crazyit.app.service"/> </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(); }
三 Bean
Chinese
package org.crazyit.app.service.impl; import org.springframework.stereotype.*; import javax.annotation.*; import org.crazyit.app.service.*; @Component public class Chinese implements Person { private Axe axe; // axe的setter方法 @Resource(name="stoneAxe") public void setAxe(Axe axe) { this.axe = axe; } // 實(shí)現(xiàn)Person接口的useAxe()方法 public void useAxe() { // 調(diào)用axe的chop()方法, // 表明Person對(duì)象依賴于axe對(duì)象 System.out.println(axe.chop()); } }
SteelAxe
package org.crazyit.app.service.impl; import org.springframework.stereotype.*; import org.crazyit.app.service.*; @Component public class SteelAxe implements Axe { public String chop() { return "鋼斧砍柴真快"; } }
StoneAxe
package org.crazyit.app.service.impl; import org.springframework.stereotype.*; import org.crazyit.app.service.*; @Component public class StoneAxe implements Axe { public String chop() { return "石斧砍柴好慢"; } }
四 測(cè)試類
package lee; import org.springframework.context.*; import org.springframework.context.support.*; import org.crazyit.app.service.*; public class BeanTest { public static void main(String[] args) { // 創(chuàng)建Spring容器 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); Person person = ctx.getBean("chinese" , Person.class); person.useAxe(); } }
五 測(cè)試結(jié)果
石斧砍柴好慢
更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Spring框架入門與進(jìn)階教程》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。