06-Spring5设置创建 bean实例是单实例还是多实例

1.单实例bean

在 Spring 里面,默认情况下,bean 是单实例对象. 单例对象在容器里只有一个.
在这里插入图片描述
User类

package com.limi.test;
import org.springframework.beans.factory.FactoryBean;

public class User{

    private String name;

    public void setName(String name) {
        this.name = name;
    }
}

测试类

package com.limi.test;

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

public class MyTest {

    @Test
    public void test1(){
        //1.加载bean的xml文件, 以src为根目录
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

        //2.获取配置的对象, 参数1:bean的id值, 参数2: 类名.class
        User user1 = context.getBean("User", User.class);
        User user2 = context.getBean("User", User.class);

        //3.使用对象
        System.out.println("user1:"+user1);
        System.out.println("\nuser2:"+user2);
    }
}

测试结果, 可以看到user1和user2是同一个实例
在这里插入图片描述

2.多实例bean

  • 多实例bean, 一个类的对象在容器里可以有多个实例.
  • 在 spring 配置文件 bean 标签里面有属性(scope)用于设置单实例还是多实例,scope=singleton 对应单实例, scope=prototype对应多实例.
  • 设置 scope 值是 singleton 时候,加载 spring 配置文件时候就会创建单实例对象 ,设置 scope 值是prototype 时候,不是在加载 spring 配置文件时候创建对象,在调用 getBean 方法时候创建多实例对象.
<?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">

    <!--id是唯一标识, class是全类名    -->
    <bean id="User" class="com.limi.test.User" scope="prototype">
        <property name="name" value="andy"></property>
    </bean>

</beans>

测试结果, 可以看到user1和user2是两个不同的实例
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值