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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乐只乐之

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值