You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调试时无需依赖注入与ApplicationContextAware获取Spring上下文的方法

在Spring中不依赖注入获取应用上下文的方案

Spring本身没有提供开箱即用的SomeSpringClass.getCurrentContext()静态方法,但可以通过以下几种符合要求的方案实现调试时直接获取上下文:

1. 自定义静态上下文持有类

这是最通用的方案,通过一个被Spring管理的类内部持有上下文,调用方直接静态调用即可,完全不需要依赖注入:

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextHolder {
    private static ApplicationContext applicationContext;

    public static ApplicationContext getCurrentContext() {
        return applicationContext;
    }

    // 仅内部初始化使用,调用方无需关注
    @Override
    public void setApplicationContext(ApplicationContext context) {
        SpringContextHolder.applicationContext = context;
    }
}

调试时直接调用:

ApplicationContext ac = SpringContextHolder.getCurrentContext();

Spring会自动扫描并初始化这个类,无需额外配置。

2. Spring Boot环境下直接复用启动类上下文

如果是Spring Boot应用,可以在启动类中直接保存上下文的引用,调试时直接调用:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class YourApplication {
    public static ApplicationContext appContext;

    public static void main(String[] args) {
        appContext = SpringApplication.run(YourApplication.class, args);
    }
}

调试调用:

ApplicationContext ac = YourApplication.appContext;

3. 通过BeanFactoryPostProcessor持有上下文

另一种实现方式,利用Spring的BeanFactoryPostProcessor机制初始化上下文持有类:

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class StaticContextHolder implements BeanFactoryPostProcessor, ApplicationContextAware {
    private static ApplicationContext context;

    public static ApplicationContext getCurrentContext() {
        return context;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        // 空实现,仅用于触发Spring加载该类
    }

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

调用方式:

ApplicationContext ac = StaticContextHolder.getCurrentContext();

内容的提问来源于stack exchange,提问作者Hassen Gaaya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 04:55:13