Spring管理的bean的作用域

我们在实例化bean的时候就会有一个疑惑,通过getBean方法得到的bean对象是同一个bean对象,还是不同的bean对象。下面具体讨论bean的作用域。
1,默认情况下的作用域

<?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-2.5.xsd">
          <bean id="personService" class="yanxi.service.implement.PersonServiceBean"></bean>
</beans>

springTest.java

package junit.test;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import yanxi.service.PersonService;

public class SpringTest {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    @Test public void instanceSpring(){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        PersonService personService1 = (PersonService)ctx.getBean("personService");
        PersonService personService2 = (PersonService)ctx.getBean("personService");
    System.out.println(personService1==personService2);
    }
}

输出结果为 true
根据输出结果显示,在默认情况下,spring实例化bean得到的都是同一个对象,即bean的作用域是在spring容器中。
2,scope=”singleton”
更改配置文件bean的scope属性

<?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-2.5.xsd">
          <bean id="personService" class="yanxi.service.implement.PersonServiceBean" scope="singleton"></bean>
</beans>

输出结果为 true
根据输出结果显示,在scope=”singleton”下,spring实例化bean得到的都是同一个对象,即bean的作用域是在spring容器中。
3,scope=”prototype”
更改配置文件bean的scope属性

<?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-2.5.xsd">
          <bean id="personService" class="yanxi.service.implement.PersonServiceBean" scope="prototype"></bean>
</beans>

输出结果为 false
根据输出结果显示,在scope=”prototype”下,spring实例化bean得到的不是同一个对象。

第一种第二种情况下,都体现了spring使用了单例模式的特点

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值