Spring系列 Aware接口解读(超通俗易懂版)


一、Aware接口源码

如下代码,Aware是一个空的接口,该接口并未定义方法。看注释说:Aware是一个标记作用的接口,具体方法由子类去定义和实现,实现该接口的bean会被Spring以回调的方式进行通知、告诉某个阶段某件事情发生了。

/**
 * 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.
 *
 * <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接口的作用

  • 通过Aware接口可以获取Spring容器相关信息
  • @Autowired等注解的解析需要用到bean后处理器,属于是扩展功能,但是Aware接口属于是内置功能,不加任何扩展,Spring就能识别出。
  • Spring 提供Aware接口机制,给外部的类提供获取spring内部信息的能力。

通俗一点讲:就比如:若Spring检测到bean实现了Aware接口,则会为其注入相对应的依赖,所以通过让bean实现Aware接口,则能在bean中获得对应的容器资源

三、常用Aware接口和作用

类名作用
BeanNameAware获得容器中bean的名称
BeanClassLoaderAware获得类加载器
BeanFactoryAware获得bean工厂
EnvironmentAware获得环境变量
EmbeddedValueResoverAware获得Spring容器加载的properties文件属性值
ApplicationEventPublisherAware获得应用时间发布器
MessageSourceAware获得文本信息
ApplicationContextAware获得当前应用上下文

在这里插入图片描述

四、案例

虚拟场景:Spring中管理的对象分为两类,一类是用户自定义的对象,一类是Spring容器对象,比如Application BeanFactory等。用户自定义的对象,在注入时可以直接使用@Autowared等方法,但是如果需要使用容器对象,该怎么注入呢?

这个时候 我们考虑Spring的一个扩展方法:ApplicationContextAware接口,实现容器对象的注入

接口源码:

public interface ApplicationContextAware extends Aware {
    void setApplicationContext(ApplicationContext var1) throws BeansException;
}

如何使用:

创建即ApplicationContextAware接口的实现类,实现类中定义局部变量applicationContext,实现setApplicationContext方法,将容器对象接收到applicationContext中。

@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtil.applicationContext = applicationContext;
    }

    public static <T> T getBean(String beanName) {
        return (T)applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> className) {
        return applicationContext.getBean(className);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值