Spring框架設(shè)值注入操作實戰(zhàn)案例分析
更新時間:2019年11月15日 12:01:14 作者:cakincqm
這篇文章主要介紹了Spring框架設(shè)值注入操作,結(jié)合具體實例形式分析了spring框架設(shè)值注入相關(guān)實現(xiàn)與使用方法,需要的朋友可以參考下
本文實例講述了Spring框架設(shè)值注入操作。分享給大家供大家參考,具體如下:
一 配置
<?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實例,其實現(xiàn)類是Chinese類 --> <bean id="chinese" class="org.crazyit.app.service.impl.Chinese"> <!-- 驅(qū)動調(diào)用chinese的setAxe()方法,將容器中stoneAxe作為傳入?yún)?shù) --> <property name="axe" ref="stoneAxe"/> </bean> <!-- 配置stoneAxe實例,其實現(xiàn)類是StoneAxe --> <bean id="stoneAxe" class="org.crazyit.app.service.impl.StoneAxe"/> <!-- 配置steelAxe實例,其實現(xiàn)類是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(); }
三 實現(xiàn)
Chinese
package org.crazyit.app.service.impl; import org.crazyit.app.service.*; public class Chinese implements Person { private Axe axe; // 設(shè)值注入所需的setter方法 public void setAxe(Axe axe) { this.axe = axe; } // 實現(xiàn)Person接口的useAxe方法 public void useAxe() { // 調(diào)用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 { // 創(chuàng)建Spring容器 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // 獲取chinese 實例 Person p = ctx.getBean("chinese" , Person.class); // 調(diào)用useAxe()方法 p.useAxe(); } }
五 運行
石斧砍柴好慢
更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Spring框架入門與進階教程》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計有所幫助。
相關(guān)文章
SpringBoot從配置文件中獲取屬性的四種方法總結(jié)
這篇文章主要介紹了SpringBoot從配置文件中獲取屬性的四種方法總結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02SpringBoot+JPA?分頁查詢指定列并返回指定實體方式
這篇文章主要介紹了SpringBoot+JPA?分頁查詢指定列并返回指定實體方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12