Spring(16) Aware结尾的类整理

目录

      • [一、什么是 Aware 结尾的类?](#一、什么是 Aware 结尾的类?)
      • [二、常见的 Aware 实现接口](#二、常见的 Aware 实现接口)
      • [三、Aware 实现原理](#三、Aware 实现原理)

一、什么是 Aware 结尾的类?

在 Spring Boot 中,以 Aware 结尾的类通常是一些继承了 Aware 接口的接口类,它们用于使 Bean 获取某些特定的能力或资源。这些接口提供了回调方法,当 Bean 被 Spring 容器初始化时,Spring 会在适当的时机调用这些方法,从而将相应的能力或资源注入到 Bean 中。

Spring 中 Aware 接口的源码如下:

java 复制代码
package org.springframework.beans.factory;

/**
 * A marker superinterface indicating that a bean is eligible to be notified by the
 * Spring container of a particular framework object through a callback-style method.
 * The actual method signature is determined by individual subinterfaces but should
 * typically consist of just one void-returning method that accepts a single argument.
 * ------------------------------
 * 一个标记的超接口,指示 bean 有资格通过回调样式的方式由特定框架对象的 Spring 容器通知。实际
 * 的方法签名由各个子接口决定,但通常应该只包含一个接受单个参数的空返回方法。
 *
 * <p>Note that merely implementing {@link Aware} provides no default functionality.
 * Rather, processing must be done explicitly, for example in a
 * {@link org.springframework.beans.factory.config.BeanPostProcessor}.
 * Refer to {@link org.springframework.context.support.ApplicationContextAwareProcessor}
 * for an example of processing specific {@code *Aware} interface callbacks.
 * ------------------------------
 * 注意,仅仅实现 Aware 不提供默认功能。相反,处理必须显式地完成,例如在 org.springframework.beans.factory.config.BeanPostProcessor 中。
 * 请参阅 org.springframework.context.support.ApplicationContextAwareProcessor,以获取处理特定 *Aware 接口回调地示例。
 *
 * @author Chris Beams
 * @author Juergen Hoeller
 * @since 3.1
 */
public interface Aware {

}

二、常见的 Aware 实现接口

以下是几个常见的 Aware 的实现接口及其作用:

  1. ApplicationContextAware:允许 Bean 获取对 ApplicationContext 的引用,以便能够访问 Spring 容器的功能、配置和其他 Bean。
  2. BeanFactoryAware:允许 Bean 获取对 BeanFactory 的引用,以便能够访问 Spring 容器的工厂方法。
  3. EnvironmentAware:允许 Bean 获取对 Environment 的引用,以便能够访问 Spring 应用程序的配置环境。
  4. ResourceLoaderAware:允许 Bean 获取对 ResourceLoader 的引用,以便能够加载外部资源,如文件、URL等。
  5. ServletContextAware:允许 Bean 获取对 ServletContext 的引用,以便能够与 Servlet API 进行交互。

通过实现这些 Aware 接口,并对相应的回调方法进行处理,可以在 Spring Boot 应用程序中方便地获取和使用相应的能力或资源。

三、Aware 实现原理

在 Spring Boot 中,ApplicationContextAware 为例,是通过 ApplicationContextAwareProcessor 来初始化的。

ApplicationContextAwareProcessor 是一个 BeanPostProcessor (后置处理器),它会在 Spring 容器初始化 Bean 时扫描类路径,检查哪些 Bean 实现了 ApplicationContextAware 接口,并在实例化 Bean 后,通过回调方式将 ApplicationContext 注入到 Bean 中。

之前的文章有介绍过,Spring 中 Bean 的生命周期如下:

我们在图中可以看到,当 Bean 在执行完依赖注入之后就开始调用 Aware 接口的相关实现类了。其实具体来说这一步应该归属于 BeanPostProcessor#before 这一过程。

BeanPostProcessor 是用于增强 Bean 功能的后置处理器,其中封装了 before 和 after 两个方法,分别在 Bean 的初始化前后执行,源码如下:

java 复制代码
package org.springframework.beans.factory.config;

import org.springframework.beans.BeansException;
import org.springframework.lang.Nullable;

public interface BeanPostProcessor {
    
	@Nullable
	default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}
    
	@Nullable
	default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}
}

ApplicationContextAware 为例,它是通过 ApplicationContextAwareProcessor 类进行调用的,ApplicationContextAwareProcessor 类实现了 BeanPostProcessor 接口的 before 方法:

java 复制代码
class ApplicationContextAwareProcessor implements BeanPostProcessor {
    @Override
	@Nullable
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
				bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
				bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)){
			return bean;
		}

		AccessControlContext acc = null;

		if (System.getSecurityManager() != null) {
			acc = this.applicationContext.getBeanFactory().getAccessControlContext();
		}

		if (acc != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareInterfaces(bean);
				return null;
			}, acc);
		}
		else {
			invokeAwareInterfaces(bean);
		}

		return bean;
	}

	private void invokeAwareInterfaces(Object bean) {
		...
		if (bean instanceof ApplicationContextAware) {
			((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
		}
	}
}

所以,Aware 是通过 BeanPostProcessor 后置处理的 before 方法,在 Bean 进行初始化之前执行了相关操作,将某些特定的能力或资源赋予 Bean

整理完毕,完结撒花~ 🌻

相关推荐
宇图SHARE1 分钟前
别再用 Python 写 Agent 前端了!Vue3 + NestJS + TypeScript 全栈方案,开发效率翻倍
前端·后端
吃饱了得干活3 分钟前
Spring Cloud Gateway限流:从Redis到Sentinel的三种方案
后端·spring cloud
奇牙coding6 分钟前
gpt-5.6-luna 调用报 400 bad_request 怎么办?同样的 messages 在 gpt-5.5 没问题——两处校验差异和修复写法
java·windows·gpt·ai
IT_陈寒9 分钟前
Python的GIL让我以为CPU跑满了,结果...
前端·人工智能·后端
Jiude16 分钟前
AI 产品的几种付费方式
后端·架构·openai
凤山老林22 分钟前
从“无法创建本地线程“异常说起:深度解析线程栈与JVM线程优化指南
java·开发语言·jvm
聚美智数1 小时前
常见疾病查询-疾病症状—疾病介绍-疾病大全-疾病治疗查询API接口介绍
android·java·数据库
慧都小妮子1 小时前
Aspose.Words for JasperReports v26.6 发布,底层Java大升级
java·pdf·报表工具·aspose.words·文档转换·报表导出·jasperreports
白宇横流学长1 小时前
基于SSM医院电子病历管理系统的设计与实现
java
观远数据1 小时前
经营闭环的最后一公里:从看见问题到解决问题之间还差什么
java·开发语言·数据库