spring回顧系列:Scope

    scope描述的是spring容器如何新建bean的實例。

    可通過@scope註解來配置,spring的scope有以下幾種:

  1. Singleton:spring的默認配置,一個spring容器中只有一個Bean的實例,全局共享一個實例;

  2. Prototype:每次調用都新建一個實例;
  3. Request:web項目中,給每一個http request請求都新建一個實例;
  4. Session:web項目中,給每一個http session都新建一個實例;
  5. GlobalSession:只在portal應用中有用,給每一個global http session都新建一個實例。
  • 演示

@Service//默認scope爲singleton
public class DemoService {

}

以上爲singleton模式,即單例模式。

@Service
@Scope("prototype")//聲明爲prototype,每次調用都新建一個bean實例
public class DemoPrototypeService {

}

配置

@Configuration
@ComponentScan("com.ys.base.mocktest")
public class Config {

}

比較區別

public class Application {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = 
				new AnnotationConfigApplicationContext(Config.class);
		DemoService demoService1 = context.getBean(DemoService.class);
		DemoPrototypeService demoPrototypeService1 = 
                                context.getBean(DemoPrototypeService.class);
		
		DemoService demoService2 = context.getBean(DemoService.class);
		DemoPrototypeService demoPrototypeService2 = 
                                context.getBean(DemoPrototypeService.class);
		System.out.println("singleton----->" + 
                                demoService1.equals(demoService2));//true
		System.out.println("prototype----->" + 
                                demoPrototypeService1.equals(demoPrototypeService2));//false
		
		context.close();
	}
}

結果

singleton----->true
prototype----->false
通過結果可得,singleton全程只創建一個bean實例;而prototype每次調用都創建了一個bean實例。

但是在實際開發過程中,我們一般都是採用默認形式singleton單例模式。


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