spring回顾系列:Scope
来源:互联网 发布:用手机怎么开淘宝店? 编辑:程序博客网 时间:2024/04/27 14:10
scope描述的是spring容器如何新建bean的实例。
可通过@scope注解来配置,spring的scope有以下几种:
Singleton:spring的默认配置,一个spring容器中只有一个Bean的实例,全局共享一个实例;
- Prototype:每次调用都新建一个实例;
- Request:web项目中,给每一个http request请求都新建一个实例;
- Session:web项目中,给每一个http session都新建一个实例;
- GlobalSession:只在portal应用中有用,给每一个global http session都新建一个实例。
演示
@Service//默认scope为singletonpublic 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));//trueSystem.out.println("prototype----->" + demoPrototypeService1.equals(demoPrototypeService2));//falsecontext.close();}}
结果
singleton----->trueprototype----->false通过结果可得,singleton全程只创建一个bean实例;而prototype每次调用都创建了一个bean实例。
但是在实际开发过程中,我们一般都是采用默认形式singleton单例模式。
阅读全文
0 0
- spring回顾系列:Scope
- spring回顾系列:AOP
- spring回顾系列:多线程
- spring回顾系列:依赖注入
- spring回顾系列:定时任务
- spring scope
- spring scope
- Spring-scope
- Spring Scope
- Spring scope
- Spring-scope
- Spring Scope
- spring Scope
- Spring Scope
- Spring Scope
- Spring Scope
- spring scope
- Spring Scope
- AsyncTask的基本使用及工作原理
- 命令行调用ARMCC编译STM32
- Bitmap二次采样
- hihoCode #1338 : A Game (区间dp)
- 3191: [JLOI2013]卡牌游戏
- spring回顾系列:Scope
- 006-题目:判断101-200之间有多少个素数,并输出所有素数。
- 虚拟机的创建和管理
- HTML计算机代码元素
- 笨方法学python 41:来自 Percal 25 号行星的哥顿人 (Gothons)
- dlopen failed: couldn't map ... Permission denied
- 【机器学习】 Matlab 2015a 自带机器学习算法汇总
- 第三章ThreadLoacl的使用
- mysql基本操作快速复习-增删改查