Spring(五)基于XML装配bean(作用域)

36 篇文章 1 订阅
16 篇文章 6 订阅

bean的作用域

用于确定Spring创建bean实例的个数
默认为singleton
可以用scope进行配置

scope取值

这里写图片描述
我们常用的:
singleton:单例模式(servlet)
prototype:多例,即执行一次getBean便获得一个实例.(struct-action)

测试

测试流程

Users类
xml配置
junit测试
修改xml文件bean的scope
junit

singleton

Users类

package com.scx.scope.test;

public class Users {
    private Integer uid;
    private String username;
    private Integer age;

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

}

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="UsersId" class="com.scx.scope.test.Users" scope="singleton"></bean>
</beans>

junit测试

package com.scx.scope.test;

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

public class Test {
    @org.junit.Test
    public void testScope() {
        String xmlPath = "com/scx/scope/test/applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                xmlPath);
        Users user1 = applicationContext.getBean("UsersId", Users.class);
        Users user2 = applicationContext.getBean("UsersId", Users.class);
        System.out.println(user1);
        System.out.println(user2);
        System.out.println(user1==user2);
    }
}

运行结果
这里写图片描述
两次输出的结果一样 ,为单例模式

prototype

修改xml文件bean的scope为prototype

    <bean id="UsersId" class="com.scx.scope.test.Users" scope="prototype"></bean>

运行结果:
这里写图片描述
两次输出的结果不同,为多例
由此可以知道可以通过对scope的设置来确定生成bean的方式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值