一、在 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.nucsoft.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.nucsoft.spring.bean.Employee@1ed71887
com.nucsoft.spring.bean.Employee@1ed71887

2.prototype(原型),每次调用 getBean() 都会返回一个新的实例

<bean class="com.nucsoft.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.nucsoft.spring.bean.Employee@652e3c04
com.nucsoft.spring.bean.Employee@3e665e81

 

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

 

相关文章:

  • 2021-11-21
  • 2021-08-08
  • 2021-08-10
  • 2022-01-02
猜你喜欢
  • 2021-10-28
  • 2021-04-23
  • 2021-07-18
  • 2021-07-23
相关资源
相似解决方案