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实例
本文介绍了Spring框架中Bean的两种实例化方式及五种作用域,重点探讨了单例模式(Singleton)和原型模式(Prototype)的区别。通过示例演示了在不同作用域下Bean实例的创建过程。
2543

被折叠的 条评论
为什么被折叠?



