【问题标题】:Other ways of kickstarting Spring Boot instead of SpringApplication.run启动 Spring Boot 而不是 SpringApplication.run 的其他方式
【发布时间】:2020-10-10 19:23:58
【问题描述】:
我只是好奇除了使用 SpringApplication.run() 方法之外,还有其他方法可以运行或启动 Spring Boot 应用程序。例如,AnnotationConfigApplicationContext 可以启动应用程序吗?为什么?你能列出一些其他的方式并加以区分吗?
【问题讨论】:
-
您可以做run() 方法所做的事情,但您为什么要这样做?无论如何,看看run()的源代码。用好 IDE 就很容易做到,如果用不好 IDE(不做就傻了),也可以在线查看source code。
标签:
java
spring
spring-boot
【解决方案1】:
在核心中spring boot之前,我们需要处理应用上下文
然后从那里,我们必须获取下一个正在运行的服务类 bean,而不是调用该方法。
XmlBaseConfiguration 或 AnnotationBaseConfiguration 也有两种方式
public class XmlBaseConfiguration {
public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext(
"META-INF/spring-context.xml");
HelloWorld hw = (HelloWorld) appContext.getBean("helloWorld");
String output = hw.getValueFromContext("strHelloWorld");
System.out.print(output);
}
}
或
public class AnnotationBaseConfiguration {
public static void main(String[] args) {
ApplicationContext appContext = new AnnotationConfigApplicationContext(Configuration.class);
HelloWorld hw = (HelloWorld) appContext.getBean("helloWorld");
String output = hw.getValueFromContext("strHelloWorld");
System.out.print(output);
}
}