案例06 Bean的作用域案例

分别使用singleton和prototype作用域创建Bean实例,比较singleton和prototype作用域的区别。

1. 创建项目

Idea创建Java项目,项目名称为:case06-spring-student05。

2. 导入spring相关jar包

case05-spring-student04项目下创建lib目录,在lib目录下导入Jar包:

  • 核心包

spring-core-5.3.25.jar

spring-beans-5.3.25.jar

spring-context-5.3.25.jar

spring-expression-5.3.25.jar

  • 测试包

junit-4.6.jar

  • 依赖包

commons-logging-1.2.jar

3. 创建Spring配置文件

src目录下创建applicationContext.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="singletonBean" class="com.wfit.student.SingletonBean" scope="singleton"/>
    <!--原型模式-->
    <bean id="prototypeBean" class="com.wfit.student.PrototypeBean" scope="prototype"/>
</beans>

4. 创建SingletonBean类

src目录下创建com.wfit.student包,此包目录下创建SingletonBean类。

public class SingletonBean {
    public SingletonBean(){
        System.out.println("singleton...");
    }
}

5. 创建PrototypeBean类

com.wfit.student目录下创建PrototypeBean类。

public class PrototypeBean {
    public PrototypeBean(){
        System.out.println("prototype...");
    }
}

6. 创建测试类

src目录下创建com.wfit.test包,此包目录下创建TestStudent测试类。

public class TestStudent {
    @Test
    public void testSingleton(){
        //初始化Spring容器ApplicationContext,加载配置文件
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        SingletonBean bean1 = applicationContext.getBean("singletonBean",SingletonBean.class);
        SingletonBean bean2 = applicationContext.getBean("singletonBean",SingletonBean.class);
        System.out.println(bean1 == bean2);
    }
    @Test
    public void testPrototype(){
        //初始化Spring容器ApplicationContext,加载配置文件
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        PrototypeBean bean1 = applicationContext.getBean("prototypeBean",PrototypeBean.class);
        PrototypeBean bean2 = applicationContext.getBean("prototypeBean",PrototypeBean.class);
        System.out.println(bean1 == bean2);
    }
}

7. 执行结果

  • testSingleton执行结果

​testPrototype执行结果

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

田园Coder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值