Spring Boot 使用配置文件启用/禁用嵌入式 tomcat [英] Spring boot enable/disable embedded tomcat with profile
问题描述
我正在编写一个 Spring Boot 应用程序,它使用几个 @Configuration
类之一,具体取决于 application.properties
中设置的 @Profile
代码>文件.
I'm writing a Spring Boot application that uses one of several @Configuration
classes depending on which @Profile
is set in the application.properties
file.
其中一个配置类使用 REST 接口,因此我将 spring-boot-starter-web
作为依赖项包含在内.
One of those Configuration classes uses a REST interface, and therefore I'm including spring-boot-starter-web
as a dependency.
这会启动一个嵌入式 Tomcat 实例,这很好.
This starts up an embedded Tomcat instance, which is fine.
问题是,其他配置文件不需要嵌入式服务器(例如,我使用 JMS 而不是 REST 来处理传入消息).
The problem is, the other profiles don't need an embedded server (e.g. I'm using JMS to handle incoming messages instead of REST).
有什么办法可以阻止 @SpringBootApplication
默认启动 Tomcat,并且只将其用于 REST 配置类?例如,通过使用 @EnableWebMVC
Is there any way to stop the @SpringBootApplication
from starting up Tomcat by default, and only using it for the REST Configuration class?
E.g., by annotating that class with @EnableWebMVC
这是我的 @Configuration
类的示例:
Here's an example of my @Configuration
classes:
休息:
@Profile({"REST"})
@Configuration
@EnableWebMvc
public class HttpConfiguration{
.
.
.
}
JMS:
@Profile({"JMS"})
@Configuration
@EnableJms
public class JMSConfiguration{
.
.
.
}
谢谢
推荐答案
使用
@SpringBootApplication(exclude = {EmbeddedServletContainerAutoConfiguration.class,
WebMvcAutoConfiguration.class})
排除 Spring Boot 对嵌入式 servlet 容器的自动配置.此外,您需要为非 REST 情况设置以下属性,以便 Spring Boot 不会尝试启动 WebApplicationContext
(需要一个 servlet 容器):
to exclude Spring Boot's auto-configuration for embedded servlet containers. Additionally, you need to set the following property for the non-REST cases, so that Spring Boot won't try to start a WebApplicationContext
(which needs a servlet container):
spring.main.web-environment=false
然后通过导入 EmbeddedServletContainerAutoConfiguration.class
在您的 REST 配置文件中启用嵌入式 Tomcat(这会将自动配置延迟到 REST 配置文件加载后:
Then enable the embedded Tomcat in your REST profile by importing EmbeddedServletContainerAutoConfiguration.class
(this delays the autoconfiguration until after the REST profile has been loaded:
@Profile({"REST"})
@Configuration
@Import(EmbeddedServletContainerAutoConfiguration.class)
public class HttpConfiguration {
// ...
}
如果您使用任何EmbeddedServletContainerCustomizer
,您还需要导入EmbeddedServletContainerCustomizerBeanPostProcessorRegistrar.class
.
If you are using any EmbeddedServletContainerCustomizer
s, you also need to import EmbeddedServletContainerCustomizerBeanPostProcessorRegistrar.class
.
这篇关于Spring Boot 使用配置文件启用/禁用嵌入式 tomcat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!