package com.example.mqttbroker.config;
  • 声明这个类所在的包,方便 Java 项目管理和引用。
  • com.example.mqttbroker.config 表示它属于 MQTT Broker 项目的配置类包。

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
  • 导入了几个核心类:

    1. BeansException:Spring Bean 异常基类,用于处理 Bean 获取或初始化过程中的异常。
    2. ApplicationContext:Spring 的核心接口,代表整个 Spring 容器,可以用来获取 Bean、发布事件、读取配置等。
    3. ApplicationContextAware:接口,允许实现类在 Spring 初始化时获取到 ApplicationContext 对象。
    4. Component:Spring 注解,表示这个类是一个组件,Spring 容器会自动扫描并注册它。

@Component
public class SpringContextHolder implements ApplicationContextAware {
  • @Component

    • 告诉 Spring 这个类是一个组件,Spring 容器启动时会创建这个类的实例并管理它。
  • implements ApplicationContextAware

    • 表示这个类实现了 ApplicationContextAware 接口。
    • Spring 在创建这个 Bean 时,会调用接口中的 setApplicationContext() 方法,将 Spring 容器的 ApplicationContext 传入。

    private static ApplicationContext context;
  • 声明一个 静态变量 context,用于存储 Spring 容器实例。

  • 静态变量意味着:

    • 无需创建 SpringContextHolder 对象就可以访问它。
    • 方便在非 Spring 管理的类中调用 SpringContextHolder.getBean() 获取 Bean。

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.context = applicationContext;
    }
  • 重写 ApplicationContextAware 接口的方法:

    • Spring 容器启动并创建这个 Bean 后,会自动调用这个方法。
    • 参数 applicationContext 就是 Spring 容器的实例。
  • SpringContextHolder.context = applicationContext;

    • 将 Spring 容器保存到静态变量中,这样全局都可以使用。
  • 注意:如果在 Spring 容器未初始化前调用 getBean(),会抛出异常(后面有处理)。


    public static <T> T getBean(Class<T> type) {
  • 定义一个 泛型方法

    • T 是泛型类型,根据传入的类型返回对应的 Bean。
    • Class<T> type 是传入的 Bean 类型,例如 MyService.class
  • 静态方法意味着可以直接用 SpringContextHolder.getBean(MyService.class) 获取 Bean,而无需依赖注入。


        if (context == null) {
            throw new IllegalStateException("Spring ApplicationContext not initialized yet");
        }
  • 检查 context 是否已经被 Spring 注入:

    • 如果 context 为空,说明 Spring 容器还未初始化或 SpringContextHolder 尚未被创建。
    • 抛出 IllegalStateException,防止空指针异常并提醒开发者。

        return context.getBean(type);
    }
  • 调用 Spring 容器的 getBean(Class<T>) 方法:

    • 返回指定类型的 Bean。
    • 可以直接在普通类或静态方法中使用,不需要依赖注入。

✅ 总结功能

  1. SpringContextHolder 是一个工具类,用来在非 Spring 管理的类中获取 Spring Bean

  2. 核心思路:

    • 利用 ApplicationContextAware 接口获取 Spring 容器实例。
    • 将容器实例保存为静态变量。
    • 提供静态方法 getBean(),全局访问 Bean。
  3. 典型使用场景:

    • 静态工具类需要调用 Spring 管理的服务。
    • 定时任务类(@Scheduled 方法)不方便注入 Bean 时。
    • MQTT Broker、Netty 等非 Spring 组件中需要访问 Spring Bean。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐