這篇文章主要介紹Spring框架設值注入操作的示例分析,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
一 配置
<?xml version="1.0" encoding="GBK"?> <!-- Spring配置文件的根元素,使用spring-beans-4.0.xsd語義約束 --> <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實例,其實現類是Chinese類 --> <bean id="chinese" class="org.crazyit.app.service.impl.Chinese"> <!-- 驅動調用chinese的setAxe()方法,將容器中stoneAxe作為傳入參數 --> <property name="axe" ref="stoneAxe"/> </bean> <!-- 配置stoneAxe實例,其實現類是StoneAxe --> <bean id="stoneAxe" class="org.crazyit.app.service.impl.StoneAxe"/> <!-- 配置steelAxe實例,其實現類是SteelAxe --> <bean id="steelAxe" class="org.crazyit.app.service.impl.SteelAxe"/> </beans>
二 接口
Axe
package org.crazyit.app.service; public interface Axe { // Axe接口里有個砍的方法 public String chop(); }
Person
package org.crazyit.app.service; public interface Person { // 定義一個使用斧子的方法 public void useAxe(); }
三 實現
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; } // 實現Person接口的useAxe方法 public void useAxe() { // 調用axe的chop()方法, // 表明Person對象依賴于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 "鋼斧砍柴真快"; } }
四 測試類
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 { // 創建Spring容器 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // 獲取chinese 實例 Person p = ctx.getBean("chinese" , Person.class); // 調用useAxe()方法 p.useAxe(); } }
以上是“Spring框架設值注入操作的示例分析”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。