歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Spring基礎—— Bean 的作用域

Spring基礎—— Bean 的作用域

日期:2017/3/1 9:14:06   编辑:Linux編程

一、在 Spring Config 文件中,在 <bean> 元素的 scope 屬性裡設置 Bean 的作用域。默認為 singleton ,單例的。

二、在不引入 spring-web-4.0.0.RELEASE.jar 包的情況下,scope 屬性只有兩個值:singleton 和 prototype。

1.singleton(單例)

Spring 為每個在 IOC 容器中聲明的 Bean 創建一個實例,整個 IOC 容器范圍都能共用。通過 getBean() 返回的對象為同一個對象。

如:

<bean class="com.linuxidc.spring.bean.Employee" id="employee" p:empName="emp01" p:age="12"/>
@Test
public void test01() {
  Employee employee = ctx.getBean(Employee.class);
  System.out.println(employee);

  Employee employee2 = ctx.getBean(Employee.class);
  System.out.println(employee2);
}

控制台輸出:

com.linuxidc.spring.bean.Employee@1ed71887
com.linuxidc.spring.bean.Employee@1ed71887

2.prototype(原型),每次調用 getBean() 都會返回一個新的實例

<bean class="com.linuxidc.spring.bean.Employee" id="employee" p:empName="emp01" p:age="12" scope="prototype"/>
@Test
 public void test01() {
  Employee employee = ctx.getBean(Employee.class);
  System.out.println(employee);

  Employee employee2 = ctx.getBean(Employee.class);
  System.out.println(employee2);
}

控制台輸出:

com.linuxidc.spring.bean.Employee@652e3c04
com.linuxidc.spring.bean.Employee@3e665e81

這裡不對 web 環境的 Bean 的作用域進行討論,事實上,我們常用到的也就這兩種。

Spring中如何配置Hibernate事務 http://www.linuxidc.com/Linux/2013-12/93681.htm

Struts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htm

基於 Spring 設計並實現 RESTful Web Services http://www.linuxidc.com/Linux/2013-10/91974.htm

Spring-3.2.4 + Quartz-2.2.0集成實例 http://www.linuxidc.com/Linux/2013-10/91524.htm

使用 Spring 進行單元測試 http://www.linuxidc.com/Linux/2013-09/89913.htm

運用Spring注解實現Netty服務器端UDP應用程序 http://www.linuxidc.com/Linux/2013-09/89780.htm

Spring 3.x 企業應用開發實戰 PDF完整高清掃描版+源代碼 http://www.linuxidc.com/Linux/2013-10/91357.htm

Spring 的詳細介紹:請點這裡
Spring 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved