设为首页 加入收藏

TOP

day04-Spring管理Bean-IOC-02(三)
2023-07-25 21:42:13 】 浏览:75
Tags:day04-Spring 管理 Bean-IOC-02

Cat:

package com.li.bean;

/**
 * @author 李
 * @version 1.0
 */
public class Cat {
    private Integer id;
    private String name;

    public Cat() {
        System.out.println("Cat() 构造器被执行...");
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

beans.xml:

<!--配置 Cat对象
    1.默认情况下,scope属性的值为 "singleton",即ioc容器中只会有一个这样的bean对象
        当执行getBean时,返回的是同一个对象
    2.如果希望每次使用getBean都返回新的Bean对象,就要把scope的属性设为 prototype
-->
<bean id="cat" class="com.li.bean.Cat">
    <property name="id" value="10"/>
    <property name="name" value="小花猫"/>
</bean>

测试类:

//测试Scope
@Test
public void testBeanScope() {
    ApplicationContext ioc = new ClassPathXmlApplicationContext("beans.xml");
    Cat cat1 = ioc.getBean("cat", Cat.class);
    Cat cat2 = ioc.getBean("cat", Cat.class);
    Cat cat3 = ioc.getBean("cat", Cat.class);
    System.out.println("cat1="+cat1);
    System.out.println("cat2="+cat2);
    System.out.println("cat3="+cat3);
}

输出如下:地址值相同,证明这三个对象引用都指向了同一个对象

image-20230117204736245

例子2-多例对象

现在我们把例子1的cat对象的配置改为scope="prototype"

<bean id="cat" class="com.li.bean.Cat" scope="prototype">
    <property name="id" value="10"/>
    <property name="name" value="小花猫"/>
</bean>

输出如下:构造器执行了三次,说明创建了三个Cat对象(对象的地址值也不一样)

image-20230117205237652

使用细节:

  1. 当bean为scope="singleton"(默认值),在启动容器时,就会创建单例对象,并放入singletonObjects集合

  2. 当bean设置为scope="prototype",即设置为多实例机制后,该bean是在getBean时才创建

  3. 如果是单例singleton,但又希望在getBean时才创建,可以指定懒加载lazy-init="true" (默认值是false)

  4. 通常情况下,lazy-init 使用默认值false,因为在开发看来,用空间换时间是值得的,除非有特殊要求。

  5. 如果scope="prototype",这时你的lazy-init属性值不管设置为什么,都默认为true

    因为多例情况下,spring无法知道创建几个对象,因此只有在用到的时候才能创建

首页 上一页 1 2 3 4 5 下一页 尾页 3/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇使用 Elasticsearch 搭建自己的搜.. 下一篇gRPC之初体验

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目