1. 程式人生 > 程式設計 >Spring框架設值注入操作實戰案例分析

Spring框架設值注入操作實戰案例分析

本文例項講述了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();
  }
}

五 執行

石斧砍柴好慢

更多關於java相關內容感興趣的讀者可檢視本站專題:《Spring框架入門與進階教程》、《Java資料結構與演算法教程》、《Java操作DOM節點技巧總結》、《Java檔案與目錄操作技巧彙總》和《Java快取操作技巧彙總》

希望本文所述對大家java程式設計有所幫助。