Spring中Bean的作用域
Spring中Bean的作用域
在Spring中可以通过配置bean标签的scope属性来指定bean的作用域范围
singleton(默认):在IOC容器中,这个bean的对象始终为单实例。也就是表示获取该bean所对应的对象都是同一个
prototype:这个bean在IOC容器中有多个实例。也就是表示获取该bean所对应的对象都不是同一个
另外,在WebApplicationContext环境下还会有另外两个作用域(不常用),一个是request,一个是session
以下为bean的单例测试:
<bean id="student" class="com.qcw.spring.pojo.Student" scope="singleton">
<property name="sid" value="1001"></property>
<property name="sname" value="张三"></property>
</bean>
public class ScopeTest {
@Test
public void testScope(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-scope.xml");
Student student1 = ioc.getBean(Student.class);
Student student2 = ioc.getBean(Student.class);
System.out.println(student1 == student2);
}
}
可以得到结果获取到的bean所对应的对象是同一个
还没有评论,来说两句吧...