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

整理完毕,完结撒花~ 🌻

相关推荐
团子的二进制世界5 分钟前
G1垃圾收集器是如何工作的?
java·jvm·算法
long31610 分钟前
Aho-Corasick 模式搜索算法
java·数据结构·spring boot·后端·算法·排序算法
独断万古他化20 分钟前
【SSM开发实战:博客系统】(三)核心业务功能开发与安全加密实现
spring boot·spring·mybatis·博客系统·加密
rannn_11137 分钟前
【苍穹外卖|Day4】套餐页面开发(新增套餐、分页查询、删除套餐、修改套餐、起售停售)
java·spring boot·后端·学习
灵感菇_39 分钟前
Java HashMap全面解析
java·开发语言
qq_124987075341 分钟前
基于JavaWeb的大学生房屋租赁系统(源码+论文+部署+安装)
java·数据库·人工智能·spring boot·计算机视觉·毕业设计·计算机毕业设计
短剑重铸之日1 小时前
《设计模式》第十一篇:总结
java·后端·设计模式·总结
若鱼19191 小时前
SpringBoot4.0新特性-Observability让生产环境更易于观测
java·spring
觉醒大王1 小时前
强女思维:着急,是贪欲外显的相。
java·论文阅读·笔记·深度学习·学习·自然语言处理·学习方法
努力学编程呀(๑•ี_เ•ี๑)1 小时前
【在 IntelliJ IDEA 中切换项目 JDK 版本】
java·开发语言·intellij-idea