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
相关产品推荐
相关产品推荐

