spring学习笔记(六)bean的作用域

IOC操作Bean管理(bean作用域)

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

2、在Spring里面,默认情况下,bean是单实例对象。

示例如下:

Book.class:

package Module;

public class Book {
    private int ID;
    private String name;
    public int getID() {
        return ID;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

    public String getName() {
        return name;
    }

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

bean1.xml:

<?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="book" class="Module.Book"></bean>
</beans>

MainTest:

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import Module.Book;
public class MainTest
{
    @Test
    public void MainTest()
    {
        ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
        Book book1=context.getBean("book",Book.class);
        Book book2=context.getBean("book",Book.class);
        System.out.println(book1);
        System.out.println(book2);
    }
}

由此可见book1与book2的地址是相同的,Spring里,默认的bean是单实例对象。

3、如何设置单实例或多实例:

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

(2)scope属性值

第一个值:默认值,singleton,表示单实例对象。

第二个值prototype,表示多实例对象。

设置多实例对象:

将bean1.xml里的scope属性设置为prototype:

<?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="book" class="Module.Book" scope="prototype"></bean>
</beans>

测试结果:

可见,book1与book2的地址不相同

(3)singleton和prototype区别

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

第二:设置scope值是singleton时候,加载spring配置文件时候就会创建单实例对象。

设置scope值是prototype时候,不是在加载spring配置文件时候创建对象,在调用getBean方法时候创建多实例对象。

另外scope还有两个值:request和session,

当scope值变为request时,每创建一个对象会放到request这个域对象中

当scope值变为session时,每创建一个对象会放到session中(web基础,session和request)

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值