Spring启用/禁用带有配置文件的嵌入式tomcat

问题描述 投票:19回答:3

我正在编写一个Spring Boot应用程序,该应用程序使用几个@Configuration类中的一个,具体取决于@Profilefile中设置的application.properties

其中一个Configuration类使用REST接口,因此我将spring-boot-starter-web作为依赖项。

这启动了一个嵌入式Tomcat实例,这很好。

问题是,其他配置文件不需要嵌入式服务器(例如,我使用JMS来处理传入的消息而不是REST)。

是否有任何方法可以阻止@SpringBootApplication默认启动Tomcat,并且仅将它用于REST配置类?例如,通过用@EnableWebMVC注释该类

这是我的@Configurationclasses的一个例子:

休息:

@Profile({"REST"})
@Configuration
@EnableWebMvc
public class HttpConfiguration{
 .
 .
 .
}

JMS:

@Profile({"JMS"})
@Configuration
@EnableJms
public class JMSConfiguration{
 .
 .
 .
}

谢谢

spring spring-mvc tomcat spring-boot
3个回答
28
投票

使用

@SpringBootApplication(exclude = {EmbeddedServletContainerAutoConfiguration.class, 
                                  WebMvcAutoConfiguration.class})

排除Spring Boot的嵌入式servlet容器的自动配置。此外,您需要为非REST情况设置以下属性,以便Spring Boot不会尝试启动WebApplicationContext(需要servlet容器):

spring.main.web-environment=false

然后通过导入EmbeddedServletContainerAutoConfiguration.class在您的REST配置文件中启用嵌入式Tomcat(这会延迟自动配置,直到加载REST配置文件之后:

@Profile({"REST"})
@Configuration
@Import(EmbeddedServletContainerAutoConfiguration.class)
public class HttpConfiguration {
    // ...
}

如果您使用任何EmbeddedServletContainerCustomizers,您还需要导入EmbeddedServletContainerCustomizerBeanPostProcessorRegistrar.class


15
投票

来自@hzpz和@orid的答案让我走上正轨。

我需要补充一下

@SpringBootApplication(exclude = {EmbeddedServletContainerAutoConfiguration.class, 
WebMvcAutoConfiguration.class})

并设置:

spring.main.web-environment=false

在我的application.properties文件中的非Rest案例。


8
投票

从Spring Boot 2.0开始,相关配置文件中只有spring.main.web-application-type=none可以解决问题。

如果您使用带有Spring Boot 2.0的多文档application.yml,则添加此块并将no-web-profile-name替换为不应具有嵌入式Web服务器的配置文件应该可以正常工作:

---
spring:
  profiles: no-web-profile-name
  main:
    web-application-type: none
© www.soinside.com 2019 - 2024. All rights reserved.