Spring Aware 接口

Spring Aware 接口

Spring框架中的Aware接口是一个特殊的标记接口,用表示该 Bean 可以接受 Spring容器特定的对象。

in short 实现这些内置子接口的Bean, Spring 在实例化时过程中会调用其方法, 将Spring框架特定的对象注入

org.springframework.beans.factory.Aware

/**
 * 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.
 *
 * Spring框架中的`Aware`接口是一个特殊的标记接口,用表示该 Bean 可以接受 Spring容器特定的对象。
 * 注意 `Aware` 接口仅作为一个标记, 实际的注入对象, 由各个子接口方法的签名确定
 *
 * <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.
 *
 * @author Chris Beams
 * @author Juergen Hoeller
 * @since 3.1
 */
public interface Aware {

}


Aware 的子接口

Pasted image 20251122163439

相关注入的源码

ApplicationContextAwareProcessor 是一个 BPP 它本身会在容器启动准备BeanFactory 的过程中org.springframework.context.support.AbstractApplicationContext#prepareBeanFactory 添加到 beanFactory 中

/**
 * Configure the factory's standard context characteristics,
 * such as the context's ClassLoader and post-processors.
 * @param beanFactory the BeanFactory to configure
 */
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// Tell the internal bean factory to use the context's class loader etc.
	/**
	 * 为 beanFactory 设置 bean 的类加载器
	 */
	beanFactory.setBeanClassLoader(getClassLoader());
	/**
	 * 为 beanFactory 设置 bean 的表达式(Spring EL)解析器
	 */
	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));

	/**
	 *  为 beanFactory 设置 PropertyEditorRegistrar
	 */
	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

	/**
	 * <!>添加一个 BeanPostProcessor 回调, 作用是如果Bean实现这些接口:
	 * (bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
	 * 				bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
	 * 				bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware ||
	 * 				bean instanceof ApplicationStartupAware)
	 *  它负责调用其对应 Aware 的方法, 给Bean 注入对象
	 *
	 * in short 就是给 bean 设置 上下文, 内置的对象; 注意是 (postProcessBeforeInitialization)
	 */
	// Configure the bean factory with context callbacks.
	beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
......

org.springframework.context.support.ApplicationContextAwareProcessor 的源码

package org.springframework.context.support;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.Aware;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.EmbeddedValueResolver;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationStartupAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.lang.Nullable;
import org.springframework.util.StringValueResolver;

/**
 * {@link BeanPostProcessor} implementation that supplies the {@code ApplicationContext},
 * {@link org.springframework.core.env.Environment Environment}, or
 * {@link StringValueResolver} for the {@code ApplicationContext} to beans that
 * implement the {@link EnvironmentAware}, {@link EmbeddedValueResolverAware},
 * {@link ResourceLoaderAware}, {@link ApplicationEventPublisherAware},
 * {@link MessageSourceAware}, and/or {@link ApplicationContextAware} interfaces.
 *
 * <p>Implemented interfaces are satisfied in the order in which they are
 * mentioned above.
 *
 * <p>Application contexts will automatically register this with their
 * underlying bean factory. Applications do not use this directly.
 *
 * @author Juergen Hoeller
 * @author Costin Leau
 * @author Chris Beams
 * @author Sam Brannen
 * @since 10.10.2003
 * @see org.springframework.context.EnvironmentAware
 * @see org.springframework.context.EmbeddedValueResolverAware
 * @see org.springframework.context.ResourceLoaderAware
 * @see org.springframework.context.ApplicationEventPublisherAware
 * @see org.springframework.context.MessageSourceAware
 * @see org.springframework.context.ApplicationContextAware
 * @see org.springframework.context.support.AbstractApplicationContext#refresh()
 */
class ApplicationContextAwareProcessor implements BeanPostProcessor {

	private final ConfigurableApplicationContext applicationContext;

	private final StringValueResolver embeddedValueResolver;


	/**
	 * Create a new ApplicationContextAwareProcessor for the given context.
	 */
	public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
		this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
	}


	@Override
	@Nullable
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		/**
		 * 这里只处理以下的7种对象的 Aware注入, 若不是则返回不处理
		 */
		if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
				bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
				bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware ||
				bean instanceof ApplicationStartupAware)) {
			return bean;
		}
		//
		invokeAwareInterfaces(bean);
		return bean;
	}

	private void invokeAwareInterfaces(Object bean) {
		if (bean instanceof Aware) {
			if (bean instanceof EnvironmentAware environmentAware) {
				environmentAware.setEnvironment(this.applicationContext.getEnvironment());
			}
			if (bean instanceof EmbeddedValueResolverAware embeddedValueResolverAware) {
				embeddedValueResolverAware.setEmbeddedValueResolver(this.embeddedValueResolver);
			}
			if (bean instanceof ResourceLoaderAware resourceLoaderAware) {
				resourceLoaderAware.setResourceLoader(this.applicationContext);
			}
			if (bean instanceof ApplicationEventPublisherAware applicationEventPublisherAware) {
				applicationEventPublisherAware.setApplicationEventPublisher(this.applicationContext);
			}
			if (bean instanceof MessageSourceAware messageSourceAware) {
				messageSourceAware.setMessageSource(this.applicationContext);
			}
			if (bean instanceof ApplicationStartupAware applicationStartupAware) {
				applicationStartupAware.setApplicationStartup(this.applicationContext.getApplicationStartup());
			}
			if (bean instanceof ApplicationContextAware applicationContextAware) {
				applicationContextAware.setApplicationContext(this.applicationContext);
			}
		}
	}

}

  1. Environment 对象。Environment对象代表了当前应用运行的环境,它可以用来获取配置属性(如系统属性、环境变量、配置文件中的属性等)。通过Environment,可以方便地访问各种配置信息,并且支持 profiles 和 properties 的解析。
  2. EmbeddedValueResolver对象。这个对象用于解析字符串中的占位符(如${...})和SpEL表达式(如#{...})。它通常用于注解驱动或XML配置中,用于解析嵌入在字符串中的值。
  3. ResourceLoader 是用于加载资源(如类路径下的文件、文件系统中的文件、URL资源等)的策略接口。ApplicationContext 本身就是一个ResourceLoader,所以这里将applicationContext作为ResourceLoader注入。
  4. ApplicationEventPublisher 对象。这个对象用于发布应用事件。Spring的事件机制是基于观察者模式的,通过ApplicationEventPublisher发布事件,然后由相应的ApplicationListener监听器处理。这里同样使用 applicationContext 作为事件发布器,因为ApplicationContext实现了ApplicationEventPublisher接口。
  5. MessageSource 是用于国际化(i18n)的消息接口,它可以解析消息代码并返回对应的消息字符串。通过MessageSource,可以实现多语言支持。
  6. ApplicationStartup 是Spring 5.3引入的,用于跟踪应用启动过程中的各个步骤,从而可以收集启动性能指标。它允许开发者监控应用启动的各个阶段。
  7. ApplicationContext 是Spring容器的核心接口,它提供了配置应用上下文的功能,包括获取bean、发布事件、访问环境、国际化等功能。通过实现这个接口,bean可以直接访问容器,但通常不推荐这样做,因为这样会导致代码与Spring框架耦合。

另外

BeanNameAware BeanClassLoaderAwareBeanFactoryAware 是在 BeanFactory 创建bean 的过程中调用的, 它们优先于上面的7个

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition)

/**
	 * Initialize the given bean instance, applying factory callbacks
	 * as well as init methods and bean post processors.
	 * <p>Called from {@link #createBean} for traditionally defined beans,
	 * and from {@link #initializeBean} for existing bean instances.
	 * @param beanName the bean name in the factory (for debugging purposes)
	 * @param bean the new bean instance we may need to initialize
	 * @param mbd the bean definition that the bean was created with
	 * (can also be {@code null}, if given an existing bean instance)
	 * @return the initialized bean instance (potentially wrapped)
	 * @see BeanNameAware
	 * @see BeanClassLoaderAware
	 * @see BeanFactoryAware
	 * @see #applyBeanPostProcessorsBeforeInitialization
	 * @see #invokeInitMethods
	 * @see #applyBeanPostProcessorsAfterInitialization
	 */
	@SuppressWarnings("deprecation")
	protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {

		/**
		 * 先调用这三个 BeanNameAware, BeanClassLoaderAware, BeanFactoryAware
		 * 这三个是在创建 BeanFactory 时忽略的三个 Aware 接口
		 * { @link org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#AbstractAutowireCapableBeanFactory() }
		 *
		 */
		invokeAwareMethods(beanName, bean);

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			/**
			 * 调用所有 BeanPostProcessors#postProcessBeforeInitialization
			 * (作用 在Bean初始化之前调用)
			 * 比如 Spring 中Aware属性的设置, 是通过这种方式扩展的
			 * - org.springframework.context.support.ApplicationContextAwareProcessor
			 * 对应调用 ApplicationContextAware, EnvironmentAware, ApplicationEventPublisherAware 等Aware方法
			 *
			 */
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			/**
			 * 调用 init-method 方法
			 */
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					(mbd != null ? mbd.getResourceDescription() : null), beanName, ex.getMessage(), ex);
		}
		if (mbd == null || !mbd.isSynthetic()) {
			/**
			 * 调用所有 BeanPostProcessors#postProcessAfterInitialization
			 *
			 */
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

		return wrappedBean;
	}

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeAwareMethods

	private void invokeAwareMethods(String beanName, Object bean) {
		if (bean instanceof Aware) {
			if (bean instanceof BeanNameAware beanNameAware) {
				//BeanNameAware 接口 调用
				beanNameAware.setBeanName(beanName);
			}
			if (bean instanceof BeanClassLoaderAware beanClassLoaderAware) {
				ClassLoader bcl = getBeanClassLoader();
				if (bcl != null) {
					//BeanClassLoaderAware 接口 调用
					beanClassLoaderAware.setBeanClassLoader(bcl);
				}
			}
			if (bean instanceof BeanFactoryAware beanFactoryAware) {
				//BeanFactoryAware 接口 调用
				beanFactoryAware.setBeanFactory(AbstractAutowireCapableBeanFactory.this);
			}
		}
	}
posted @ 2025-11-23 20:57  daidaidaiyu  阅读(111)  评论(0)    收藏  举报