Spring入门(五):Spring Bean Scope讲解

1. 前情回顾

Spring入门(一):建立Spring项目java

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

Spring入门(三):经过JavaConfig装配beangithub

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

2. 什么是Bean的Scope?

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

Spring经常使用的Scope有如下几种,经过**@Scope**注解来实现:post

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

3. 示例

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

3.1 新建Singleton类型的Bean

package scope;

import org.springframework.stereotype.Service;

@Service
public class DemoSingletonService {
}
复制代码

由于Spring默认配置的Scope是Singleton,所以以上代码等价于如下代码:spa

package scope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope("singleton")
public class DemoSingletonService {
}
复制代码

3.2 新建ProtoType类型的Bean

package scope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope("prototype")
public class DemoPrototypeService {
}
复制代码

3.3 新建配置类

package scope;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("scope")
public class ScopeConfig {
}
复制代码

3.4 测试

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

package scope;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class);

        DemoSingletonService s1 = context.getBean(DemoSingletonService.class);
        DemoSingletonService s2 = context.getBean(DemoSingletonService.class);

        DemoPrototypeService p1 = context.getBean(DemoPrototypeService.class);
        DemoPrototypeService p2 = context.getBean(DemoPrototypeService.class);

        System.out.println("s1 与 s2 是否相等:" + s1.equals(s2));
        System.out.println("p1 与 p2 是否相等:" + p1.equals(p2));

        context.close();
    }
}
复制代码

运行结果以下:code

从运行结果也能够看出,默认状况下即Singleton类型的Bean,无论调用多少次,只会建立一个实例。

4. 注意事项

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

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

即便是大小写不一致也不行,如咱们将DemoPrototypeService类的代码修改成:

package scope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope("PROTOTYPE")
public class DemoPrototypeService {
}
复制代码

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

5. 源码

源码地址:github.com/zwwhnly/spr…,欢迎下载。

6. 参考

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

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

相关文章
相关标签/搜索