Spring IOC容器-bean的作用域

bean 的作用域

1、在 Spring 里面,可以设置创建 bean 实例是 单实例还是多实例。

2、在 Spring 里面,默认情况下, 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="person" class="com.lmgd.entity.Person">
        <property name="name" value="邓林妹"></property>
        <property name="age" value="25"></property>
    </bean>
</beans>
    @org.junit.Test
    public void testIOC() {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
        Person person1 = context.getBean("person", Person.class);
        Person person2 = context.getBean("person", Person.class);
        System.out.println(person1);
        System.out.println(person2);
    }

Spring IOC中 person1 与 person2 内存地址一样,由此可见默认是单例模式(只初始化一次)

 

如何设置单实例还是多实例? 

(1)在 Spring 配置文件 bean 标签里面有属性(scope) 用于设置单实例还是多实例

(2)scope属性值

第一个值 默认值,singleton 表示是单实例对象(只初始化一次)

第二个值 prototype,表示是多实例对象(每次请求都会生成一个新的对象)

    <bean id="person" class="com.lmgd.entity.Person" scope="prototype">
        <property name="name" value="邓林妹"></property>
        <property name="age" value="25"></property>
    </bean>

 scope属性值设置为 prototype,person对象输出的内存地址不一样:

 (3)singleton 和 prototype 区别

第一:singleton 单实例,prototype 多实例

第二:创建对象的时机不一样

1、设置 scope 值是为 singleto 时,加载 Spring 配置文件就会创建单实例对象。

调用如下代码,就会创建单实例对象:

ApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");

2、设置 scope 值为 prototype 时,不是在加载 Spring 配置文件时候创建对象,而是在调用 getBean() 方法时,创建多实例对象。

 其他(了解)

 scope 属性值还有 request、session

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值