Spring Boot启用/禁用带有配置文件的嵌入式Tomcat [英] Spring boot enable/disable embedded tomcat with profile

查看:719
本文介绍了Spring Boot启用/禁用带有配置文件的嵌入式Tomcat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个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.propertiesfile.

其中一个Configuration类使用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 Configuration类? 例如,通过用@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类的示例:

REST:

@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 EmbeddedServletContainerCustomizers, you also need to import EmbeddedServletContainerCustomizerBeanPostProcessorRegistrar.class.

这篇关于Spring Boot启用/禁用带有配置文件的嵌入式Tomcat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆