close

在Beans.xml中定義Spring Bean時,我們可以藉由其提供的Scope屬性來決定bean instance建立的方式

常會用到的有兩種:singletonprototype

1. singleton (預設即是採singleton模式)
指的是不管程式呼叫了幾次Spring Bean,都只會有一個bean的instance(類別實體) 被建立
當第一個instance被建立後就會存在於快取中,而後每當需要建立新的該bean實體時
程式都會直接使用這個被快取住的實體來重複使用,而不會再重新建立一個實體

2. prototype
跟singleton不同,若scope設定為prototype,則當每次需要建立一個instance時,
程式就會再新建一個bean的類別實體來使用

以下藉由一個例子來比較兩者的不同:
1. 撰寫一個HelloWolrd.java,內容如下:

package com.allen0818.springpractice;

/**
 *
 * @author allen0818
 */
public class HelloWorld {
  private String message;
  
  public void setMessage(String message){
    this.message = message;
  }
  
  public void getMessage(){
    System.out.println("Your message: " + message);
  }
}

2. 在Beans.xml中定義這個Bean,並將scope設定為 singleton,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">

   <bean id="helloworldWithSingleton" class="com.allen0818.springpractice.HelloWorld"
        scope="singleton">
   </bean>

</beans>

3. 最後撰寫一個用來執行程式的MainAppWithSingleton.java,內容如下:

package com.allen0818.springpractice;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author allen0818
 */
public class MainAppWithSingleton {
  public static void main(String[] args){
    ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
    
    HelloWorld objA = (HelloWorld) context.getBean("helloworldWithSingleton");
    objA.setMessage("I'm object A!!");
    objA.getMessage();
    
    HelloWorld objB = (HelloWorld) context.getBean("helloworldWithSingleton");
    objB.getMessage();
  }
}

可以看到執行結果為:

Your message: I'm object A!!
Your message: I'm object A!!

可以發現第二次被建立的Bean instance其實就是直接拿第一次建立的instance來用

那麼如果我們將scope設定為 prototype的話,執行結果就會變成下面這樣:

Your message: I'm object A!!
Your message:
null

可以發現到由於第二次建立的instance並為設定message這個參數的值,因此印出了null

以上小小筆記一下^ ^

 

參考資料來源:
1. http://www.tutorialspoint.com/spring/spring_bean_scopes.htm

 

arrow
arrow
    文章標籤
    Java EE Spring Spring framework
    全站熱搜
    創作者介紹
    創作者 allen0818 的頭像
    allen0818

    allen0818 的部落格

    allen0818 發表在 痞客邦 留言(0) 人氣()