spring学习——scope属性

scope属性

scope表示spring容器对一个bean的请求的处理方式,我们常用的设置值有:singleton(默认的)和prototype

singleton

在容器中,从请求bean到容器生命周期结束,有且仅有一个bean的实例,每次请求都返回这个,所以对应生命周期从创建到容器销毁

prototype

每次请求bean,容器都会给生成一个新的实例并返回,返回后容器就不负责这个实例的管理。实例的生命周期就给请求方去管理来。

我们看的简单的例子

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="helloWorld" class="com.test.Car" scope="singleton">
        <property name="brand" value="Spring"/>
    </bean>

</beans>

Car类

public class Car {
    private String brand;
    private String color;
    private int maxSpeed;

    public Car() {
    }

    public String getBrand() {
        return brand;
    }

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

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getMaxSpeed() {
        return maxSpeed;
    }

    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }
}

调用程序

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

    public static void main(String[] args) throws Throwable {

        ApplicationContext ctx=new ClassPathXmlApplicationContext("file:applicationContext.xml");

        Car helloWorld=(Car) ctx.getBean("helloWorld",Car.class);

        Car helloWorld1=(Car) ctx.getBean("helloWorld",Car.class);

        System.out.println(helloWorld==helloWorld1);

        System.out.println(helloWorld.toString());
        System.out.println(helloWorld1.toString());
    }
}

输出

true
com.xxx.Car@49c342bd
com.xxx.Car@49c342bd

两次获取的实例都是同一个,我们把配置文件中的

scope="singleton"

修改成

scope="prototype"

后,输出如下:

false
com.xxx.Car@5aba9dff
com.xxx.Car@11dafee2

获取实例是不一样的

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值