【问题标题】:spring-boot-starter-tomcat vs spring-boot-starter-webspring-boot-starter-tomcat 与 spring-boot-starter-web
【发布时间】:2016-01-29 22:11:45
【问题描述】:

我正在尝试学习 Spring boot,但我注意到有两种选择。

  1. spring-boot-starter-web - 根据文档,它支持全栈 Web 开发,包括 Tomcat 和 web-mvc

  2. spring-boot-starter-tomcat

既然 #1 支持 Tomcat,为什么还要使用 #2?

有什么区别?

谢谢

【问题讨论】:

    标签: spring tomcat spring-boot


    【解决方案1】:

    既然 #1 支持 Tomcat,为什么还要使用 #2?

    spring-boot-starter-web 包含spring-boot-starter-tomcat。如果不需要 spring mvc,spring-boot-starter-tomcat 可能会单独使用(包含在spring-boot-starter-web 中)。

    这里是spring-boot-starter-web的依赖层次结构:

    有什么区别?

    spring-boot-starter-web包含spring web依赖(包括spring-boot-starter-tomcat):

    spring-boot-starter
    jackson
    spring-core
    spring-mvc
    spring-boot-starter-tomcat

    spring-boot-starter-tomcat 包含与嵌入式 tomcat 服务器相关的所有内容:

    core
    el
    logging
    websocket

    如果你想在没有嵌入式tomcat服务器的情况下使用spring mvc怎么办?

    只需将其从依赖项中排除:

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    

    【讨论】:

    • 如果我想要嵌入式 tomcat 但使用不同的 tomcat 版本怎么办?正如您所提到的,我通过排除单独添加了不同版本的 starter tomcat,但仍然无法正常工作。
    【解决方案2】:

    一个简单的答案是,并非所有 Web 应用程序都是 SpringMVC 应用程序。例如,如果您希望使用 JaxRS,也许您有使用 RestTemplate 的客户端应用程序,并且您喜欢它们的交互方式,但这并不意味着您不能使用 spring boot 或嵌入式 tomcat

    这是一个使用 spring-boot-starter-tomcat 但不使用 spring-boot-starter-web 的示例应用程序

    Spring Boot 中使用 spring-boot-starter-tomcat 的简单 Jersey 应用程序

    https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-jersey

    同样重要的是要记住,tomcat 并不是 Spring Boot 中嵌入式 servlet 容器的唯一选择。使用 jetty 也很容易上手。并且拥有spring-boot-starter-tomcat 可以很容易地将所有模块排除在一个模块中,而如果它们都只是 spring-web 的一部分,那么排除 tomcat 库以引入 spring-boot-starter-jersey 将是更多的工作

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jetty</artifactId>
    </dependency>
    

    我在这里从另一个 SO 问题复制了这段代码。

    How to configure Jetty in spring-boot (easily?)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-19
      • 2019-08-23
      • 2014-04-07
      • 1970-01-01
      • 2019-10-28
      • 1970-01-01
      • 2015-07-07
      • 2023-04-04
      相关资源
      最近更新 更多