打卡1:Bean的Scope

一. 什麼是Scope?

  1. 概念
    Scope即Spring容器創建Bean的實例的方式

  2. Spring的Scope類型

    類型 解釋
    Singleton 默認配置。一個Spring容器只有一個Bean實例
    Prototype 每次調用新建一個Bean實例
    Request Web項目中,給每一個http request新建一個Bean實例
    Session Web項目中,給每一個http session新建一個Bean實例
    GlobalSession portal應用中,給每一個globe http session新建一個Bean實例

二. 舉例分析

  1. 編寫Singleton的Bean

    @Service
    @Scope("singleton")  //Spring默認即爲Singleton,可省略此註解
    public class DemoSingletonService {
    
    }
    
  2. 編寫Prototype的Bean

    @Service
    @Scope("prototype") //聲明Scope爲Prototype
    public class DemoPrototypeService {
    
    }
    
  3. 配置類

    @Configuration
    @ComponentScan("com.muzi.springboot01.chapter2")
    public class ScopeConfig {
    
    }
    
  4. 運行

    public class Main {
    
        public static void main(String[] args) {
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class);
    
            DemoSingletonService s1 = context.getBean(DemoSingletonService.class);
            DemoSingletonService s2 = context.getBean(DemoSingletonService.class);
    
            DemoPrototypeService p1 = context.getBean(DemoPrototypeService.class);
            DemoPrototypeService p2 = context.getBean(DemoPrototypeService.class);
    
            System.out.println("s1與s2是否相等:"+s1.equals(s2));
            System.out.println("p1與p2是否相等:"+p1.equals(p2));
    
            context.close();
    
        }
    }
    
  5. 運行結果
    在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章