如何检查Spring Boot是在独立模式还是嵌入式模式下运行? [英] How to check if Spring boot is running in standalone or embedded mode?
问题描述
是否有一些可靠的方法来检查spring boot是否在JAR(带有嵌入式tomcat的独立版本)或WAR(在j2ee服务器中)模式下运行?
Is there some reliable way how to check if spring boot is running in JAR (standalone with embedded tomcat) or WAR (in j2ee server) mode?
推荐答案
没有内置的API可以检查您在哪个环境中运行.最可靠的方法可能是根据应用程序的使用情况对应用程序使用不同的配置通过其main方法或SpringBootServletInitializer
子类启动.确切地,您应该做什么取决于您需要了解的原因以及个人喜好.
There's no built in API to check which environment you're running in. Probably the most robust way would be to use different configuration for your application depending on whether it's started via its main method or via its SpringBootServletInitializer
subclass. Exactly what you should do depends on your reason for needing to know and also personal preference.
例如,您可以配置一个属性,该属性可以通过Environment
,使用@Value
等进行查询:
For example, you could configure a property that you can the query via the Environment
, using @Value
, etc:
@SpringBootApplication
public class ExampleApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(ExampleApplication.class).properties(
"com.example.mode:servlet-container");
}
public static void main(String[] args) throws Exception {
new SpringApplicationBuilder(ExampleApplication.class).properties(
"com.example.mode:standalone").run(args);
}
}
除了ExampleApplication.class
之外,另一种选择是提供一个配置类,具体取决于您在哪种模式下运行:
Another option would be to provide a configuration class in addition to ExampleApplication.class
that's different depending on what mode you're running in:
@SpringBootApplication
public class ExampleApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(ExampleApplication.class,
ServletContainerConfiguration.class);
}
public static void main(String[] args) throws Exception {
new SpringApplicationBuilder(ExampleApplication.class,
StandaloneConfiguration.class).run(args);
}
}
您完全可以在ServletContainerConfiguration
或StandaloneConfiguration
中进行操作.例如,您可以发布一个记住该模式的bean,然后在需要时查询它.
Exactly what you do in ServletContainerConfiguration
or StandaloneConfiguration
is then up to you. You could, for example, publish a bean that remembers the mode and then query it whenever you need to know.
另一种选择是根据模式激活不同的配置文件.
Yet another option would be to activate different profiles depending on the mode.
这篇关于如何检查Spring Boot是在独立模式还是嵌入式模式下运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!