1. 程式人生 > 程式設計 >Spring實戰之協調作用域不同步的Bean操作示例

Spring實戰之協調作用域不同步的Bean操作示例

本文例項講述了Spring實戰之協調作用域不同步的Bean操作。分享給大家供大家參考,具體如下:

一 配置

<?xml version="1.0" encoding="GBK"?>
<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">
   <bean id="chinese" class="org.crazyit.app.service.impl.Chinese">
      <!-- Spring只要檢測到lookup-method元素,
      Spring會自動為該元素的name屬性所指定的方法提供實現體。-->
      <lookup-method name="getDog" bean="gunDog"/>
   </bean>
   <!-- 指定gunDog Bean的作用域為prototype,
   希望程式每次使用該Bean時用到的總是不同的例項 -->
   <bean id="gunDog" class="org.crazyit.app.service.impl.GunDog"
      scope="prototype">
      <property name="name" value="旺財"/>
   </bean>
</beans>

二 介面

1 Dog

package org.crazyit.app.service;
public interface Dog
{
   public String run();
}

2 Person

package org.crazyit.app.service;
public interface Person
{
   public void hunt();
}

三 實現類

GunDog

package org.crazyit.app.service.impl;
import org.crazyit.app.service.*;
public class GunDog implements Dog
{
   private String name;
   public void setName(String name)
   {
      this.name = name;
   }
   public String getName()
   {
      return name;
   }
   public String run()
   {
      return "我是一隻叫" + getName()
        + "的獵犬,奔跑迅速..." ;
   }
}

Chinese

package org.crazyit.app.service.impl;
import org.crazyit.app.service.*;
public abstract class Chinese implements Person
{
   private Dog dog;
   // 定義抽象方法,該方法用於獲取被依賴Bean
   public abstract Dog getDog();
   public void hunt()
   {
      System.out.println("我帶著:" + getDog() + "出去打獵");
      System.out.println(getDog().run());
   }
}

四 測試類

package lee;
import org.springframework.context.*;
import org.springframework.context.support.*;
import org.crazyit.app.service.*;
public class SpringTest
{
  public static void main(String[] args)
  {
    // 以類載入路徑下的beans.xml作為配置檔案,建立Spring容器
    ApplicationContext ctx = new
      ClassPathXmlApplicationContext("beans.xml");
    Person p1 = ctx.getBean("chinese",Person.class);
    Person p2 = ctx.getBean("chinese",Person.class);
    // 由於chinese Bean是singleton行為,
    // 因此程式兩次獲取的chinese Bean是同一個例項。
    System.out.println(p1 == p2);
    p1.hunt();
    p2.hunt();
  }
}

五 測試結果

true
我帶著:org.crazyit.app.service.impl.GunDog@69a3d1d出去打獵
我是一隻叫旺財的獵犬,奔跑迅速...
我帶著:org.crazyit.app.service.impl.GunDog@86be70a出去打獵
我是一隻叫旺財的獵犬,奔跑迅速...

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

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