Spring基础—— Bean 的作用域

一、在 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);
}

控制台输出:

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);
}

控制台输出:

这里不对 web 环境的 Bean 的作用域进行讨论,事实上,我们常用到的也就这两种。

Spring 的详细介绍请点这里
Spring 的下载地址请点这里

猜你喜欢

转载自www.linuxidc.com/Linux/2016-07/133311.htm