2019-06-21 18:18 by 申城异乡人, 阅读, 评论, 收藏, 编辑

Spring入门(一):创建Spring项目

Spring入门(二):自动化装配bean

Spring入门(三):通过JavaConfig装配bean

Spring入门(四):使用Maven管理Spring项目

Scope描述的是Spring容器是如何新建Bean的实例的。

Spring常用的Scope有以下几种,通过@Scope注解来实现:

  1. Singleton:一个Spring容器中只有一个Bean的实例,即全容器共享一个实例,这是Spring的默认配置。
  2. ProtoType:每次调用新建一个Bean的实例。
  3. Request:Web项目中,给每一个http request新建一个Bean实例。
  4. Session:Web项目中,给每一个http session新建一个Bean实例。

为了更好的理解,我们通过具体的代码示例来理解下Singleton与ProtoType的区别。

  1. package scope;
  2. import org.springframework.stereotype.Service;
  3. @Service
  4. public class DemoSingletonService {
  5. }

因为Spring默认配置的Scope是Singleton,因此以上代码等价于以下代码:

  1. package scope;
  2. import org.springframework.context.annotation.Scope;
  3. import org.springframework.stereotype.Service;
  4. @Service
  5. @Scope("singleton")
  6. public class DemoSingletonService {
  7. }
  1. package scope;
  2. import org.springframework.context.annotation.Scope;
  3. import org.springframework.stereotype.Service;
  4. @Service
  5. @Scope("prototype")
  6. public class DemoPrototypeService {
  7. }
  1. package scope;
  2. import org.springframework.context.annotation.ComponentScan;
  3. import org.springframework.context.annotation.Configuration;
  4. @Configuration
  5. @ComponentScan("scope")
  6. public class ScopeConfig {
  7. }

新建一个Main类,在main()方法中,分别从Spring容器中获取2次Bean,然后判断Bean的实例是否相等:

  1. package scope;
  2. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  3. public class Main {
  4. public static void main(String[] args) {
  5. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class);
  6. DemoSingletonService s1 = context.getBean(DemoSingletonService.class);
  7. DemoSingletonService s2 = context.getBean(DemoSingletonService.class);
  8. DemoPrototypeService p1 = context.getBean(DemoPrototypeService.class);
  9. DemoPrototypeService p2 = context.getBean(DemoPrototypeService.class);
  10. System.out.println("s1 与 s2 是否相等:" + s1.equals(s2));
  11. System.out.println("p1 与 p2 是否相等:" + p1.equals(p2));
  12. context.close();
  13. }
  14. }

运行结果如下:

从运行结果也可以看出,默认情况下即Singleton类型的Bean,不管调用多少次,只会创建一个实例。

Singleton类型的Bean,@Scope注解的值必须是:singleton。

ProtoType类型的Bean,@Scope注解的值必须是:prototype。

即使是大小写不一致也不行,如我们将DemoPrototypeService类的代码修改为:

  1. package scope;
  2. import org.springframework.context.annotation.Scope;
  3. import org.springframework.stereotype.Service;
  4. @Service
  5. @Scope("PROTOTYPE")
  6. public class DemoPrototypeService {
  7. }

此时运行代码,就会报错:

源码地址:https://github.com/zwwhnly/spring-action.git,欢迎下载。

《Java EE开发的颠覆者:Spring Boot实战》

欢迎扫描下方二维码关注公众号:申城异乡人。

版权声明:本文为zwwhnly原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/zwwhnly/p/11066162.html