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

Spring Boot的main方法中如何获取ApplicationContext?

实现方案

SpringApplication.run() 方法的返回值本身就是ApplicationContext实例,直接接收该返回值即可,Spring Boot 2.6版本原生支持该用法,无需额外配置。

补全后的完整代码

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

@SpringBootApplication
public class DemoBootApplication {

   public static void main(String[] args) {
      // 接收run方法返回值得到ApplicationContext
      ApplicationContext applicationContext = SpringApplication.run(DemoBootApplication.class, args);

      // 方式1:强转获取Bean
      GreetService myService = (GreetService) applicationContext.getBean("myGreetService");
      
      // 方式2:指定类型避免强转(更推荐)
      // GreetService myService = applicationContext.getBean("myGreetService", GreetService.class);
   }

}

注意事项

  • 代码中用到的ApplicationContext导入路径为org.springframework.context.ApplicationContext,IntelliJ 2021.2.3会自动提示补全导入,无需手动查找路径。
  • 如果你没有为GreetService自定义Bean名称,Spring默认会将类名首字母小写作为Bean名称,比如类名为GreetService时默认Bean名是greetService,需要和你getBean时传入的名称保持一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 14:54:08