ApplicationContextAware学习--存疑问题

本文详细解释了如何通过实现 ApplicationContextAware 接口来自动注入 Spring 的 ApplicationContext 对象,进而获取 Spring 容器中的 Bean。同时提出了两个关于 Spring 框架实现原理的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近看项目中的代码,发现有个获取spring bean的地方,直接调用了那个获取bean的方法,但是不明白这个bean到底是怎么来的,查了一下:

先看下ApplicationContextAware的源码:

package org.springframework.context;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.Aware;

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

我们可以看到,ApplicationContextAware继承了Aware接口,我们在看下这个接口中怎么定义的:

package org.springframework.beans.factory;

public abstract interface Aware
{
}

网上查了一下,继承了ApplicationContextAware接口的类,在加载spring配置文件时,会自动调用接口中的setApplicationContext方法,并可自动获得ApplicationContext对象,前提是在spring配置文件中指定了这个类。

看下这段代码:

public class SpringContextUtils implements ApplicationContextAware
{
    private static ApplicationContext appContext;
    
    public void setApplicationContext(ApplicationContext applicationContext)
        throws BeansException
    {
        SpringContextUtils.appContext = applicationContext;
    }
    
    public static ApplicationContext getApplicationContext()
    {
        checkApplicationContext();
        return appContext;
    }
    
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName)
    {
        checkApplicationContext();
        return (T)appContext.getBean(beanName);
    }
    
    private static void checkApplicationContext()
    {
        if (null == appContext)
        {
            throw new IllegalStateException("applicaitonContext未注入");
        }
    }
}

spring配置文件中定义:

	<!-- 定义Spring工具类 -->
    <bean class="com.njxph.utils.SpringContextUtils" />

以上,就可以获取bean了。

但是我有以下几点疑问:

1、ApplicationContextAware继承了Aware接口,但是Aware接口是空的,什么都没定义,为什么ApplicationContextAware还要继承Aware接口呢?

2、为什么 继承了ApplicationContextAware接口的类,在加载spring配置文件时,会自动调用接口中的setApplicationContext方法呢?

以上,欢迎大家评论,希望各位飘过的大牛帮忙解答下,3Q


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值