Spring中Bean的作用域

深碍√TFBOYSˉ_ 2024-04-05 04:45 200阅读 0赞
Spring中Bean的作用域

在Spring中可以通过配置bean标签的scope属性来指定bean的作用域范围
singleton(默认):在IOC容器中,这个bean的对象始终为单实例。也就是表示获取该bean所对应的对象都是同一个
prototype:这个bean在IOC容器中有多个实例。也就是表示获取该bean所对应的对象都不是同一个

另外,在WebApplicationContext环境下还会有另外两个作用域(不常用),一个是request,一个是session

以下为bean的单例测试:

  1. <bean id="student" class="com.qcw.spring.pojo.Student" scope="singleton">
  2. <property name="sid" value="1001"></property>
  3. <property name="sname" value="张三"></property>
  4. </bean>
  5. public class ScopeTest {
  6. @Test
  7. public void testScope(){
  8. ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-scope.xml");
  9. Student student1 = ioc.getBean(Student.class);
  10. Student student2 = ioc.getBean(Student.class);
  11. System.out.println(student1 == student2);
  12. }
  13. }

可以得到结果获取到的bean所对应的对象是同一个

发表评论

表情:
评论列表 (有 0 条评论,200人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringBean作用

    默认情况下,`Spring`容器中所有`bean`都是以单例形式创建的,也就是说,不管给定的一个`bean`被注入到其他`bean`多少次,每次注入的都是同一个实例。 分类