spring回顾系列:Scope

来源:互联网 发布:用手机怎么开淘宝店? 编辑:程序博客网 时间:2024/04/27 14:10

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


原创粉丝点击