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

整理完毕,完结撒花~ 🌻

相关推荐
卿雪7 分钟前
Redis 线程模型:Redis为什么这么快?Redis为什么引入多线程?
java·数据库·redis·sql·mysql·缓存·golang
lkbhua莱克瓦2413 分钟前
IO流练习(修改文件中的数据)
java·windows·学习方法·io流·java练习题·io流练习
老华带你飞18 分钟前
汽车销售|汽车报价|基于Java汽车销售系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端·汽车
西岭千秋雪_29 分钟前
MySQL集群搭建
java·数据库·分布式·mysql
小马爱打代码33 分钟前
Spring AI:文生视频 - wanx2.1-i2v-plus
java·人工智能·spring
uzong37 分钟前
别让认知天花板,变成你的职业终点——技术人如何走出信息茧房
后端
华仔啊39 分钟前
RebbitMQ 入门教程看这一篇就够了
java·后端·rabbitmq
象象翔42 分钟前
AI+若依(实战篇)
java·人工智能·spring boot·spring
无限进步_43 分钟前
C语言实现贪吃蛇游戏详解
c语言·开发语言·数据结构·c++·后端·算法·游戏
CHANG_THE_WORLD1 小时前
C++ vs Python 参数传递方式对比
java·c++·python