1 创建一个普通的Scope类 该类不需要实现
package com.itheima.scope; public class Scope { }
2在配置文件中 加入bean的配置信息
<!-- scope="singleton" singleton属性的bean为单例模式 Spring默认属性为singleton --> <!-- scope="prototype" 当scope为prototype时Spring容器会对该Bean的请求都创建一个新的实例 --> <bean id="scope" class="com.itheima.scope.Scope" scope="prototype"/>
3 创建测试类ScopeTest
package com.itheima.scope; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class ScopeTest { public static void main(String [] arge){ String xmlPath = "com/itheima/scope/beans4.xml"; ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath); System.out.println(applicationContext.getBean("scope")); System.out.println(applicationContext.getBean("scope")); } }
scope="singleton" 与scope="prototype"的区别:
如果该bean的作用域为scope="singleton" 则该bean会被放入Spring ioc缓存池中,将会触发Spring对该bean的生命周期管理,singleton状态下的bean为单例模式,只有一个实例化对象
如果该bean的作用域为scope="prototype"则该bean交给调用者,调用者直接管理该bean的生命周期,Spring不再管理该bean,prototype状态下每次都会参加一个新的bean