Java学习--spring框架--入门Bean的作用域

bean的作用域决定了对于一个bean实例化的次数与方式,设置是scope属性进行设置

  • singleton:默认值,容器在初始化的时候创建bean实例。在整个容器的生命周期中只会创建一次;
  • prototype:原型,在容器初始化的时候不会去创建bean的实例,只是在每次请求时候就会创建一个新的bean实例,返回

使用默认属性的时候
配置xml文件

	<bean id="car" class="spring.autowire.Car">
        <property name="brand" value="FuTe"></property>
        <property name="price" value="30000"></property>
    </bean>

主函数

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans-scope.xml");
        Car car1 = (Car) applicationContext.getBean("car");
        Car car2 = (Car) applicationContext.getBean("car");
        System.out.println(car1 == car2);
    }

运行结果
运行结果

使用原型属性的时候

配置xml文件

    <bean id="car" class="spring.autowire.Car" scope="prototype">
        <property name="brand" value="FuTe"></property>
        <property name="price" value="30000"></property>
    </bean>

主函数

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans-scope.xml");
        Car car1 = (Car) applicationContext.getBean("car");
        Car car2 = (Car) applicationContext.getBean("car");
        System.out.println(car1 == car2);
    }

运行结果
运行结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值