一. 什麼是Scope?
-
概念
Scope即Spring容器創建Bean的實例的方式 -
Spring的Scope類型
類型 解釋 Singleton 默認配置
。一個Spring容器只有一個Bean實例Prototype 每次調用新建一個Bean實例 Request Web項目中,給每一個http request新建一個Bean實例 Session Web項目中,給每一個http session新建一個Bean實例 GlobalSession portal應用中,給每一個globe http session新建一個Bean實例
二. 舉例分析
-
編寫Singleton的Bean
@Service @Scope("singleton") //Spring默認即爲Singleton,可省略此註解 public class DemoSingletonService { }
-
編寫Prototype的Bean
@Service @Scope("prototype") //聲明Scope爲Prototype public class DemoPrototypeService { }
-
配置類
@Configuration @ComponentScan("com.muzi.springboot01.chapter2") public class ScopeConfig { }
-
運行
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(); } }
-
運行結果