Browse Source

新增spring源码学习第8章:Spring Bean 作用域笔记

seamew 2 years ago
parent
commit
088127bdad

+ 106 - 0
后端/Spring/spring源码学习/spring核心编程思想/8、Spring Bean 作用域.md

@@ -0,0 +1,106 @@
+## 第八章:Spring Bean 作用域
+
+| 作用域        | 说明                                                       |
+| ------------- | ---------------------------------------------------------- |
+| **singleton** | 默认 Spring Bean 作用域,一个 BeanFactory 有且仅有一个实例 |
+| **prototype** | 原型作用域,每次依赖查找和依赖注入生成新 Bean 对象         |
+| request       | 将 Spring Bean 存储在 ServletRequest 上下文中              |
+| session       | 将 Spring Bean 存储在 HttpSession 中                       |
+| application   | 将 Spring Bean 存储在 ServletContext 中                    |
+
+**注意事项**:
+
+- Spring 容器没有办法管理 prototype Bean 的完整生命周期,也没有办法记录示例的存
+  在。销毁回调方法将不会执行,可以利用 BeanPostProcessor 进行清扫工作。
+- **无论是 Singleton 还是 Prototype Bean 均会执行初始化方法回调,不过仅 Singleton Bean 会执行销毁方法回调**
+
+`@Scope` 注解定义原型 Bean :
+
+```java
+@Bean
+@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
+public static User prototypeUser() {
+	return createUser();
+}
+```
+
+### "request" Bean 作用域
+
+- XML - `<bean class= "..." scope = "request" />`
+- Java 注解 - `@RequestScope` 或 `@Scope(WebApplicationContext.SCOPE_REQUEST)`
+
+每次使用的 CGLIB 代理对象是同一个,但是被代理的对象每次都会重新生成。
+
+使用 IDEA 进行远程调试:
+
+- 在 Edit Configurations 中新增一个 Remote ,使用命令启动 jar 时,在启动命令中增加 Remote 里的内容,启动 jar 以及 Remote,打断点进行调试。
+
+实现 API
+
+- `@RequestScope`
+- `RequestScope`
+
+### "session" Bean 作用域
+
+配置
+
+- XML - `<bean class= "..." scope = "session" />`
+- Java 注解 - `@RequestScope` 或 `@Scope(WebApplicationContext.SCOPE_REQUEST)`
+
+实现 API
+
+- `@SessionScope`
+- `SessionScope`
+
+### "application" Bean 作用域
+
+配置
+
+- XML - `<bean class= "..." scope = "application" />`
+- Java 注解 - `@ApplicationScope` 或 `@Scope(WebApplicationContext.SCOPE_APPLICATION)`
+
+实现 API
+
+- `@ApplicationScope`
+- `ServletContextScope`
+
+实现方式与 request 和 session 不同,这里直接将 Bean 放入 `ServletContext` 中
+
+### 自定义 Bean 作用域
+
+实现 Scope
+
+- `org.springframework.beans.factory.config.Scope`
+
+注册 Scope
+
+- API
+
+  `org.springframework.beans.factory.config.ConfigurableBeanFactory#registerScope`
+
+- 配置
+
+  ```xml
+  <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
+      <property name="scopes">
+          <map>
+              <entry key="...">
+              </entry>
+          </map>
+      </property>
+  </bean>
+  ```
+
+# 面试题
+
+1、spring内建的bean作用域有几种?
+
+![image-20221013214938297](assets/image-20221013214938297.png)
+
+2、singleton bean 是否在一个应用中唯一的?
+
+![image-20221013215027472](assets/image-20221013215027472.png)
+
+3、application bean是否被其他方案代替?
+
+![image-20221013215117772](assets/image-20221013215117772.png)

BIN
后端/Spring/spring源码学习/spring核心编程思想/assets/image-20221013214938297.png


BIN
后端/Spring/spring源码学习/spring核心编程思想/assets/image-20221013215027472.png


BIN
后端/Spring/spring源码学习/spring核心编程思想/assets/image-20221013215117772.png