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单例模式。


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