標籤:位置 技術分享 學習 debug 配置 sage public 儲存 dea
Spring 架構Bean支援以下五個範圍:
下面介紹兩種範圍,singleton和protoype
singleton範圍
singleton範圍為預設範圍,在同一個ioc容器內getBean是同一個bean,如果建立一個singleton範圍Bean定義的對象執行個體,該執行個體將儲存在該Bean的緩衝中,那麼以後所有針對該 bean的請求和引用都返回緩衝對象。
編寫HelloWorld.java
1 package com.example.spring; 2 3 public class HelloWorld { 4 private String message; 5 public void setMessage(String message){ 6 this.message = message; 7 } 8 public void getMessage(){ 9 System.out.println("Your Message : " + message);10 }11 }
編寫Beans.xml,設定為singleton範圍
1 <?xml version="1.0" encoding="UTF-8"?>2 <beans xmlns="http://www.springframework.org/schema/beans"3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">5 6 <bean id="helloWorld" class="com.example.spring.HelloWorld" scope="singleton">7 </bean>8 </beans>
編寫Application.java
1 package com.example.spring; 2 3 import org.springframework.beans.factory.BeanFactory; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 public class Application { 7 public static void main(String[] args) { 8 //bean設定檔所在位置 D:\\IdeaProjects\\spring\\src\\Beans.xml 9 //使用BeanFactory容器10 BeanFactory factory = new ClassPathXmlApplicationContext("file:D:\\IdeaProjects\\spring\\src\\Beans.xml");11 HelloWorld objA = (HelloWorld)factory.getBean("helloWorld");12 objA.setMessage("I‘m object A");13 objA.getMessage();14 HelloWorld objB = (HelloWorld) factory.getBean("helloWorld");15 objB.getMessage();16 }17 }
運行輸出
Your Message : I‘m object A12:06:56.273 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean ‘helloWorld‘Your Message : I‘m object A
prototype範圍
如果範圍設定為 prototype,每次建立對象執行個體只針對當前執行個體配置Bean,getBean是不同的bean。
將上述的Beans.xml,設定為prototype範圍
1 <?xml version="1.0" encoding="UTF-8"?>2 <beans xmlns="http://www.springframework.org/schema/beans"3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">5 6 <bean id="helloWorld" class="com.example.spring.HelloWorld" scope="prototype">7 </bean>8 </beans>
運行輸出:
Your Message : I‘m object A13:52:03.767 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean ‘helloWorld‘13:52:03.767 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean ‘helloWorld‘Your Message : null
Java架構spring Boot學習筆記(三):Bean的範圍