Bean的作用域
在默認情況下,Spring應用上下文中所有的bean都是作爲單例的形式創建的。
也就是說,不管給定的一個bean被注入到其他bean多少次,每次所注入的都是同一個實例。
Spring定義了多種作用域,可以基於這些作用域創建Bean;
• 單例(singleton):在整個應用中,只創建bean的一個實例。
• 原型(prototype):每次注入或者通過Spring應用上下文獲取的時候,都會創建一個新的bean實例。
• 會話(request):在Web應用中,爲每個會話創建一個bean實例。
• 請求(session):在Web應用中,爲每個請求創建一個bean實例。
單例是默認的作用域,對於易變的類型,這並不合適。
如果選擇其它的作用域,要使用@Scope註解,它可以與@Component或@Bean註解一起使用。
上面四種,其中比較常用的是單例、原型兩種作用域。
單例作用域:每次請求該Bean都將獲得相同的實例。容器負責跟蹤Bean實例的狀態,負責維護Bean實例的生命週期行爲。
原型作用域:程序每次請求該id的bean,Spring都會新建一個bean實例,然後返回給調用者。這種情況下,Spring容器僅僅使用new關鍵字創建Bean實例,一旦創建完成,容器不再跟蹤實例,也不會維護Bean實例的狀態。
寫個小Demo看下
package com.test.spring.server.test07;
/**
* @author CYX
* @create 2018-04-30-21:37
*/
public class HelloWorld {
private String message;
public void getMessage() {
System.out.println("the message : " + message);
}
public void setMessage(String message) {
this.message = message;
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<bean id="helloWorld" class="com.test.spring.server.test07.HelloWorld"></bean>
</beans>
package com.test.spring.server.test07;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author CYX
* @create 2018-04-30-21:36
*/
public class Test07App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring/test07/applicationContext07.xml");
HelloWorld helloWorld = context.getBean("helloWorld", HelloWorld.class);
System.out.println(helloWorld);
helloWorld.setMessage("123");
helloWorld.getMessage();
HelloWorld helloWorld2 = context.getBean("helloWorld", HelloWorld.class);
helloWorld2.getMessage();
System.out.println(helloWorld2);
helloWorld2.setMessage("456");
helloWorld2.getMessage();
System.out.println(helloWorld == helloWorld2);
}
}
輸出結果:
在 bean 的配置中,沒有設置任何關於作用域的配置,所以它是默認使用單例。
看兩次打印的對象地址都是一樣。
我們在來看原型作用域
將applicationContext.xml中的配置修改一下,其他代碼不變:
<bean id="helloWorld" class="com.test.spring.server.test07.HelloWorld" scope = "prototype"/>
輸出結果:
對象兩次打印出來的內存地址也是不一樣的。
每次向Spring 請求一次,都會重新new一個對象給我....