运行 Spring RESTful 如何在 tomcat 8 下进行项目?

How to run Spring RESTful project under tomcat 8?

我正在学习下一个教程:https://spring.io/guides/gs/rest-service/

我注意到他们不使用 tomcat 来 运行 他们的项目。他们使用 "gradle run" 命令来 运行 它。 是否可以 运行 Spring 在 tomcat 下的项目?

另外,我想知道是否合理。我们需要 tomcat 到 运行 spring RESTful 项目吗(也许用 "gradle run" 命令 运行 更好)?

我正在使用 Intellij IDEA 和 gradle 3.0

我有下一个build.gradle内容:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.0.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'gs-rest-service'
    version =  '0.1.0'
}

repositories {
    jcenter()
    maven { url "http://repo.spring.io/libs-snapshot" }
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
}

全部类 和教程一样

RESTful Web 服务顾名思义是 运行 网络上的服务(HTTP 协议)。如果你想 运行 任何网络上的应用程序,你需要将其部署到 WEB SERVER.Tomcat 是一个网络 server.Yes,你需要 Tomcat((或 JBoss,Websphere,Weblogic,...server)) 到 运行 Spring 或任何 RESTful web service.Gradle 是依赖管理工具,它可以帮助您构建所需的可执行文件(如 .war 在 Web Services/applications 的情况下) .

我更喜欢 运行 Spring 使用 Idea 中的 Spring 启动 运行 配置启动项目。

只需创建一个新的 运行 配置并将 Application 指定为主 class。更多信息请见官方 documentation.

但是,您也可以 运行 它在 Tomcat 中。这意味着创建一个 Tomcat 运行 配置并在那里部署一个结果 war,但是这要麻烦得多。

如果你想使用 Spring Boot 提供的嵌入式 Tomcat,你可以只使用 spring-boot-starter-web starter 和 运行 带有 [=11= 的项目].

但是,当您按照提供的方式设置 spring-boot-starter-tomcat 时,我认为您想要使用外部 Tomcat。

在这里您可以找到 documentation 用于 WAR 创建。您需要使用 WAR gradle 插件,像往常一样配置您的 Tomcat 实例和 运行 使用 spring-boot:run 的项目。

If you’re using Gradle, you need to modify build.gradle to apply the war plugin to the project:

apply plugin: 'war'

The final step in the process is to ensure that the embedded servlet container doesn’t interfere with the servlet container to which the war file will be deployed. To do so, you need to mark the embedded servlet container dependency as provided.

dependencies { // … providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat' // … }