java 当我只想使用 RestTemplate 时,如何防止在 Spring Boot 中自动启动 tomcat/jetty

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31897165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:18:41  来源:igfitidea点击:

How to prevent auto start of tomcat/jetty in Spring Boot when I only want to use RestTemplate

javaspringspring-bootresttemplate

提问by datree

I want to use RestTemplate/TestRestTemplate by including the artifact in a SpringBoot application

我想通过在 SpringBoot 应用程序中包含工件来使用 RestTemplate/TestRestTemplate

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
    </dependency>

But this automatically starts Tomcat or Jetty. Is there a way to turn it off, or by not including the above artifact. TestRestTemplate is in the boot artifact, but not the base RestTemplate.

但这会自动启动 Tomcat 或 Jetty。有没有办法关闭它,或者不包括上述工件。TestRestTemplate 在引导工件中,但不在基础 RestTemplate 中。

回答by Stephane Nicoll

Spring Boot is not going to start a web container if it's not present. spring-webdoes not provide any embedded container. You may want to analyse the dependencies of your project (try mvn dependency:tree).

如果 Web 容器不存在,则 Spring Boot 不会启动它。spring-web不提供任何嵌入式容器。您可能想要分析项目的依赖项(尝试mvn dependency:tree)。

If you want to make sure a web server is not started in your spring boot application, you can set the following configuration key

如果你想确保你的 spring boot 应用程序中没有启动 web 服务器,你可以设置以下配置键

spring.main.web-application-type=none

Or you can use the SpringApplicationBuilder

或者你可以使用 SpringApplicationBuilder

new SpringApplicationBuilder(YourApp.class)
        .web(WebApplicationType.NONE).run(args);

回答by Tony

Since Spring Boot 2.0.0 this property is deprecated and following is the new way:

从 Spring Boot 2.0.0 开始,此属性已被弃用,以下是新方法:

spring.main.web-application-type=none

This change is because Spring Boot the support for reactive server.

这种变化是因为 Spring Boot 支持响应式服务器。

回答by barryku

You can just close the app according to https://spring.io/guides/gs/async-method/. Although this still stars Tomcat, but will stop the app at the end without keeping the tread running.

您可以根据https://spring.io/guides/gs/async-method/关闭应用程序。虽然这仍然是 Tomcat 的明星,但会在最后停止应用程序而不保持步调运行。

SpringApplication.run(MyApp.class, args).close();