1. 前情回顾
Spring 入门 (一): 创建 Spring 项目
Spring 入门 (二): 自动化装配 bean
Spring 入门 (三): 通过 JavaConfig 装配 bean
Spring 入门 (四): 使用 Maven 管理 Spring 项目
2. 什么是 Bean 的 Scope?
Scope 描述的是 Spring 容器是如何新建 Bean 的实例的.
Spring 常用的 Scope 有以下几种, 通过 @Scope 注解来实现:
Singleton: 一个 Spring 容器中只有一个 Bean 的实例, 即全容器共享一个实例, 这是 Spring 的默认配置.
ProtoType: 每次调用新建一个 Bean 的实例.
Request:web 项目中, 给每一个 http request 新建一个 Bean 实例.
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, 因此以上代码等价于以下代码:
- 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 的实例是否相等:
- 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();
- }
- }
运行结果如下:
从运行结果也可以看出, 默认情况下即 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. 源码
源码地址: https://github.com/zwwhnly/spring-action.git , 欢迎下载.
6. 参考
《Java EE 开发的颠覆者: Spring Boot 实战》
欢迎扫描下方二维码关注公众号: 申城异乡人.
来源: https://www.cnblogs.com/zwwhnly/p/11066162.html