倘伟 发表于 2025-11-23 21:30:01

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 的子接口


相关注入的源码

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);
                        }
                }
        }

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

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

喳谍 发表于 7 天前

不错,里面软件多更新就更好了

东门芳洲 发表于 4 天前

过来提前占个楼
页: [1]
查看完整版本: Spring Aware 接口