Java框架spring 學習筆記(二):Bean的做用域

Spring 框架Bean支持如下五個做用域:java

下面介紹兩種做用域,singleton和protoypespring

 

singleton做用域sql

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做用域this

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.javaspa

 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 }

運行輸出prototype

Your Message : I'm object A
Your Message : I'm object A

 

prototype做用域code

若是做用域設置爲 prototype,每次建立對象實例只針對當前實例配置Bean,getBean是不一樣的bean。xml

將上述的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 A
Your Message : null
相關文章
相關標籤/搜索