Intellij spring启动应用程序无法在tomcat中运行

3 java spring tomcat intellij-idea spring-boot

这是我的班级

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Configuration
@ComponentScan
@EnableAutoConfiguration
@SpringBootApplication
public class TomcatIc?nApplication {

    public static void main(String[] args) {
        SpringApplication.run(TomcatIc?nApplication.class, args);
    }
}

@RestController
class GreetingController {

    @RequestMapping("/hello/hi")
    String hello( ) {
        return "Hello, xx!";
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行应用程序并打开时localhost:8080/hello/hi,我可以看到输出.但是从Edit Configurations,当我在端口添加Tomcat服务器8081作为localhost:8081/hello和Tomcat运行这段时间,它调用的应用程序,并打开网页,但它是空的.

为什么我看不到我的输出?

Ali*_*ani 10

当您只运行应用程序时,Spring Boot将使用其嵌入式tomcat服务器来运行您的应用程序.如果您计划使用另一个独立的tomcat服务器来部署您的启动应用程序(我不建议),首先您应该告诉您的构建工具将您的应用程序打包为warnot jar.然后修改主引导应用程序入口点以支持它,最后war使用Intellij或手动将文件部署到tomcat服务器.

生成可部署war文件的第一步是提供SpringBootServletInitializer子类并覆盖其configure方法.在你的情况下:

@SpringBootApplication
public class TomcatIc?nApplication extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(TomcatIc?nApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(TomcatIc?nApplication.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后告诉您的构建工具将您的应用程序打包为war,而不是jar.如果你正在使用maven,只需添加:

<packaging>war</packaging>
Run Code Online (Sandbox Code Playgroud)

最后标记spring-boot-starter-tomcatprovided:

<dependencies>
    <!-- ... -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <!-- ... -->
</dependencies>
Run Code Online (Sandbox Code Playgroud)

您了解更多关于春天开机传统部署 在这里.

  • 为什么不建议在独立的tomcat服务器上运行Spring Boot应用程序? (5认同)