spring基础知识 (8): bean的作用域



在 Spring 中, 可以在 <bean> 元素的 scope 属性里设置 Bean 的作用域.

bean的五种作用域

这里写图片描述


singleton作用域

默认情况下, Spring 只为每个在 IOC 容器里声明的 Bean 创建唯一一个实例, 整个 IOC 容器范围内都能共享该实例:所有后续的 getBean() 调用和 Bean 引用都将返回这个唯一的 Bean 实例.该作用域被称为 singleton, 它是所有 Bean 的默认作用域。下面使用代码实例讲解:

  • Car类
package com.spring.ioc;

public class Car {

    private String brand;

    private double price;


    public Car() {
        System.out.println("创建Car实例...");
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car [brand=" + brand + ", price=" + price + "]";
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

注意Car类的构造函数

public Car() {
    System.out.println("创建Car实例...");
}
  • 1
  • 2
  • 3

配置bean:

<bean id="car" class="com.spring.ioc.Car" scope="singleton">
    <property name="brand" value="BMW"></property>
    <property name="price" value="1000"></property>
</bean>
  • 1
  • 2
  • 3
  • 4

测试1:

ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-scope.xml");
  • 1

运行结果:
这里写图片描述

默认情况下,bean的scope是singleton,该实例在bean容器加载时就开始创建

看下面测试:

ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-scope.xml");

Car car1 = (Car) ctx.getBean("car");

Car car2 = (Car) ctx.getBean("car");
System.out.println(car1 == car2);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

这里写图片描述

car这个bean是单例的,这也是singleton的作用,声明该bean单例


prototype作用域

将bean的scope设置为 prototype

<bean id="car" class="com.spring.ioc.Car" scope="prototype">
    <property name="brand" value="BMW"></property>
    <property name="price" value="1000"></property>
</bean>
  • 1
  • 2
  • 3
  • 4

测试1:

//加载bean容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-scope.xml");
  • 1
  • 2

测试时只加载bean容器,发现并没有创建Car实例。

测试2:

//加载bean容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-scope.xml");

Car car1 = (Car) ctx.getBean("car");

Car car2 = (Car) ctx.getBean("car");
System.out.println(car1 == car2);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

使用getBean()方法获取两个bean实例并比较
这里写图片描述

每获取一次bean都会新建一个新的bean实例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值