Spring注解驱动开发02(作用域和懒加载)

Spring中bean的作用域

默认情况下,Spring只为每个在IOC容器里声明的bean创建唯一一个实例,整个IOC容器范围内都能共享该实例:所有后续的getBean()调用和bean引用都将返回这个唯一的bean实例。该作用域被称为singleton,它是所有bean的默认作用域。
bean的作用域分类

在Spring中使用@Scope注解来设置bean的作用域

  • 不设置作用域时,两个getBean的打印结果
com.atguigu.pojo.Person@76508ed1
com.atguigu.pojo.Person@76508ed1
  • 设置多实例作用域
    @Bean
    @Scope("prototype")  //singleton默认, 改为多实例prototype
    public Person person(){
        return new Person();
    }

打印结果

com.atguigu.pojo.Person@76508ed1
com.atguigu.pojo.Person@41e36e46

懒加载@Lazy注解(只适用于单实例bean)

默认ioc容器启动的时候就创建bean对象

            try (ConfigurableApplicationContext ioc = new AnnotationConfigApplicationContext(MainConfig.class)) {
//            Person bean = ioc.getBean(Person.class);
//            Person bean2 = ioc.getBean(Person.class);
}

打印结果

创建bean

在bean对象上加上@Lazy懒加载后

    @Bean
    @Lazy
    public Person person(){
        return new Person();
    }

打印结果

      //没有getBean时,无打印
      //getBean
      创建bean
      com.atguigu.pojo.Person@50a638b5
      com.atguigu.pojo.Person@50a638b5
posted @ 2020-08-19 14:45  _五月雨  阅读(117)  评论(0编辑  收藏  举报
Live2D