Spring中Bean的作用域

Spring中Bean的实例化有两种方式,上一篇文章中我们讲过了。

Spring中Bean的作用域种类有大约五种,但是常用的有两种SingleTon和prototype

SingleTon是Spring中创建Bean的默认方式,也即单例模式;比如:

@Test

public void test() {

// 定义Spring配置文件路径

String xmlPath = "com/mengma/scope/applicationContext.xml";

// 初始化Spring容器,加载配置文件,并对bean进行实例化

ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);

// 输出获得实例

System.out.println(applicationContext.getBean("person"));

System.out.println(applicationContext.getBean("person"));

}

输出结果是两个 person bean是一样的

但是如果设置Spring的Bean为prototype时候,这两个Bean就不一样,因为对象不一样。

singleTon是spring在加载的时候就创建一个唯一的bean

prototype是spring在每次创建bean时候都会创建一个新的bean实例

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值