[英]How to get current SpringApplication instance in spring-boot programmatically?
How to get current SpringApplication instance in spring-boot programmatically? 如何以编程方式在spring-boot中获取当前的SpringApplication实例? As spring docs says : SpringApplication has a method called
isWebEnvironment()
. 如spring docs所说:SpringApplication有一个叫做
isWebEnvironment()
的方法。 I don't know how to tell if an application is a web or non-web application programmtically , can I get it from ApplicationContext.getEnvironment()
? 我不知道如何以编程方式判断应用程序是Web应用程序还是非Web应用程序,我可以从
ApplicationContext.getEnvironment()
获取它吗? By the way , I don't want to solve this by searching xxServlet
like HttpServletRequest
... etc. 顺便说一句,我不想通过搜索
HttpServletRequest
等xxServlet
来解决此问题。
What about applicationContext instanceof WebApplicationContext
? applicationContext instanceof WebApplicationContext
呢?
If you're trying to simply determine whether or not your application is running in a web context, then you can use the fact that when a Spring application is started in a web context, the ApplicationContext
object you have access to is an instance of the WebApplicationContext
interface. 如果您只是尝试确定应用程序是否在Web上下文中运行,则可以使用以下事实:在Web上下文中启动Spring应用程序时,您可以访问的
ApplicationContext
对象是该实例的实例。 WebApplicationContext
接口。 Therefore you can simply write 因此,您可以简单地写
isWebEnvironment = (applicationContext instanceof WebApplicationContext);
There is no real reason to get the SpringApplication
object from your class, as its sole purpose is to build an ApplicationContext
. 没有真正的理由从类中获取
SpringApplication
对象,因为它的唯一目的是构建ApplicationContext
。
If you are using Spring Boot
you can use this: 如果您使用的是
Spring Boot
,则可以使用以下命令:
String[] springBootAppBeanName = applicationContext.getBeanNamesForAnnotation(org.springframework.boot.autoconfigure.SpringBootApplication.class);
applicationContext.getBean(springBootAppBeanName[0]);
This will retrieve the spring bean names who are annotated with @SpringBootApplication
, after get them you can simple get the instance by his name. 这将检索用
@SpringBootApplication
注释的spring bean名称,获取它们后,您可以简单地通过其名称获取实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.