通过实现 applicationcontextaware 接口并注册为 bean,可以在非 spring 管理的类中获取 applicationcontext 进而调用 getbean() 方法。具体做法是定义一个静态变量保存上下文实例,在 setapplicationcontext 回调中赋值,随后即可在任何地方通过该静态变量获取任意 bean。需要注意的是,这种静态持有方式可能导致内存泄漏或循环依赖问题,且仅在容器完全初始化后生效。

实现 ApplicationContextAware 接口的具体步骤是什么
必须创建一个实现了 ApplicationContextAware 接口的组件,并在其中重写 setApplicationContext 方法以接收容器注入的上下文对象。将该组件标记为 @Component 或 @Configuration 中的 Bean,Spring 容器在启动时会检测到该实现并自动调用该方法完成注入。之后,通过静态字段暴露该上下文,其他类即可直接引用。

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ContextHolder implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext ctx) {
context = ctx;
}
public static <T> T getBean(Class<T> clazz) {
return context.getBean(clazz);
}
}
上述代码定义了一个全局持有的上下文工具类。当 Spring Boot 应用启动时,ContextHolder 会被实例化,setApplicationContext 被调用,此时 context 静态变量指向当前应用的唯一上下文实例。任何类只需调用 ContextHolder.getBean(MyService.class) 即可获取单例 Bean。若 Bean 不存在,将抛出 NoSuchBeanDefinitionException;若存在多个匹配类型,需使用 getBean(String name, Class<t> requiredType)</t> 指定名称以避免歧义。
使用 @Autowired 注入 ApplicationContext 与静态方式有何区别
通过 @Autowired 直接注入 ApplicationContext 是受管依赖注入的标准做法,适用于 Spring 管理的 Bean 内部使用。而静态方式适用于非 Spring 管理的类(如普通 Java 工具类、第三方库回调)需要访问容器的场景。前者生命周期由容器控制,后者需手动维护静态引用。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Autowired
private ApplicationContext context;
public void doSomething() {
// 在受管 Bean 中直接使用注入的上下文
OtherService other = context.getBean(OtherService.class);
other.execute();
}
}
在 MyService 中,context 由 Spring 自动注入,无需额外实现接口。这种方式更安全,因为 context 引用随 Bean 生命周期销毁而释放,不会造成内存泄漏。相比之下,静态方式虽然灵活,但必须在所有使用点确保容器已初始化,否则 context 为 null 会引发空指针异常。此外,静态方式无法利用 Spring 的代理机制进行事务或 AOP 增强,除非获取的是代理 Bean 本身。
在非 Web 环境(如 CommandLineRunner)中如何正确获取特定 Bean
在 CommandLineRunner 或 ApplicationListener 等早期执行阶段,容器可能尚未完全初始化所有 Bean,直接调用 getBean() 可能失败。应优先通过构造函数或方法参数注入所需 Bean,而非依赖上下文查找。若必须使用上下文,需确保在 onApplicationEvent(ContextRefreshedEvent) 事件中操作,以保证所有 Bean 已就绪。
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class EarlyInitRunner implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// 容器刷新完成后,所有单例 Bean 已创建
MyService service = event.getApplicationContext().getBean(MyService.class);
service.init();
}
}
此示例展示了在容器完全初始化后才执行逻辑的安全方式。ContextRefreshedEvent 仅在容器刷新完毕时触发一次,此时调用 getBean() 可确保目标 Bean 已实例化并完成依赖注入。若在 CommandLineRunner 中直接查找,虽通常也能成功,但在复杂依赖链下可能因初始化顺序问题导致意外行为。因此,对于关键初始化逻辑,推荐监听事件或使用构造器注入明确依赖关系。


















