Spring容器如何管理对象

时间:2024-10-13 21:20:32

1、spring容器中Bean对象的使用范围控制是,a是控制对象创建方式(使用范围),在<bean>元素中使用scope属性控制,scope可以支持singleton或prototype,默认值是singleton。

Spring容器如何管理对象

2、那么<bean scope= "singleton"> 该组件在spring容器里只有一个bean对象。每次取出的bean都是同一个bean,相当于单例模式。

Spring容器如何管理对象

3、那<bean scope = "prototype">该组件每次使用getBean("")都会返回一个新的对象,例如我们自定义了一个ExampleBean类:

Spring容器如何管理对象

4、我们在applicationContext.xml中进行配置,需要默认使用scope="singleton"。

Spring容器如何管理对象

5、那么我们需要测试一下每次取出的bean是否为同一个bean:由此可见:每次我们从容器中取出的对象都是同一个对象。

Spring容器如何管理对象
© 手抄报圈