为什么我的Spring Boot App启动后总是立即关闭?


163

这是我的第一个Spring Boot代码。不幸的是,它总是关闭。我期望它能够连续运行,以便我的Web客户端可以从浏览器中获取一些数据。

package hello;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
@EnableAutoConfiguration
public class SampleController {

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleController.class, args);
    }
}


[@localhost initial]$ java -jar build/libs/gs-spring-boot-0.1.0.jar

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::            (v1.0.0.RC4)

2014-03-13 09:20:24.805  INFO 14650 --- [           main] hello.SampleController                   : Starting SampleController on localhost.localdomain with PID 14650 (/home/xxx/dev/gs-spring-boot/initial/build/libs/gs-spring-boot-0.1.0.jar started by xxx)
2014-03-13 09:20:25.002  INFO 14650 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@b9eec: startup date [Thu Mar 13 09:20:24 EDT 2014]; root of context hierarchy
2014-03-13 09:20:28.833  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Registering beans for JMX exposure on startup
2014-03-13 09:20:30.148  INFO 14650 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2014-03-13 09:20:30.154  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'requestMappingEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=requestMappingEndpoint]
2014-03-13 09:20:30.316  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'environmentEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=environmentEndpoint]
2014-03-13 09:20:30.335  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'healthEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=healthEndpoint]
2014-03-13 09:20:30.351  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'beansEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=beansEndpoint]
2014-03-13 09:20:30.376  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'infoEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=infoEndpoint]
2014-03-13 09:20:30.400  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'metricsEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=metricsEndpoint]
2014-03-13 09:20:30.413  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'traceEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=traceEndpoint]
2014-03-13 09:20:30.428  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'dumpEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=dumpEndpoint]
2014-03-13 09:20:30.450  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'autoConfigurationAuditEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=autoConfigurationAuditEndpoint]
2014-03-13 09:20:30.465  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'shutdownEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=shutdownEndpoint]
2014-03-13 09:20:30.548  INFO 14650 --- [           main] o.s.b.a.e.jmx.EndpointMBeanExporter      : Located managed bean 'configurationPropertiesReportEndpoint': registering with JMX server as MBean [org.springframework.boot:type=Endpoint,name=configurationPropertiesReportEndpoint]
2014-03-13 09:20:30.589  INFO 14650 --- [           main] hello.SampleController                   : Started SampleController in 7.396 seconds (JVM running for 9.569)
2014-03-13 09:20:30.608  INFO 14650 --- [       Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@b9eec: startup date [Thu Mar 13 09:20:24 EDT 2014]; root of context hierarchy
2014-03-13 09:20:30.610  INFO 14650 --- [       Thread-2] o.s.c.support.DefaultLifecycleProcessor  : Stopping beans in phase 0
2014-03-13 09:20:30.624  INFO 14650 --- [       Thread-2] o.s.b.a.e.jmx.EndpointMBeanExporter      : Unregistering JMX-exposed beans on shutdown

请指教。

谢谢

PS build.gradle是错误。

dependencies {
    // tag::jetty[]
    compile("org.springframework.boot:spring-boot-starter-web") {
        **exclude module: "spring-boot-starter-tomcat"**
    }

一旦我以粗体显示了以上内容,一切正常。我的应用程序上下文现在是正确的。谢谢戴夫

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::            (v1.0.0.RC4)

2014-03-13 13:58:08.965  INFO 7307 --- [           main] hello.Application                        : Starting
 Application on  with PID 7307 (/ladev/home/xxx/dev/gs-spring-boot/initial/build/libs/gs-spring-boo
t-0.1.0.jar started by xxx)
2014-03-13 13:58:09.021  INFO 7307 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshi
ng org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@45490eb5: startup
 date [Thu Mar 13 13:58:09 MDT 2014]; root of context hierarchy
2014-03-13 13:58:09.653  INFO 7307 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overridi
ng bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=fal
se; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanNam
e=org.springframework.boot.actuate.autoconfigure.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration;
 factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class
 path resource [org/springframework/boot/actuate/autoconfigure/ErrorMvcAutoConfiguration$WhitelabelErrorView
Configuration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3;
 dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconf
igure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; in
itMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/au
toconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]

您正在使用Maven或Gradle吗?
罗曼·莫罗2014年

1
ApplicationContext的类型(AnnotationConfigApplicationContext)错误,因此它不是Web应用程序。它应该默认为一个取决于您的类路径的值,因此看起来好像是在设置或默认使用了错误的方式。也许您application.properties没有显示ENV变量?
Dave Syer 2014年

你是对的。我的ApplicationContext不正确。我没有application.properties文件。如何使其运行正确的ApplicationContext?也许是Web ApplicationContext?
johnsam 2014年

让我们尝试简化构建。您是否可以删除除spring-boot-starter-web之外的所有依赖项,然后--debug在命令行上运行with 并将日志发布回此处?
Dave Syer 2014年

戴夫,由于回复时间太长,我更新了我的原始帖子。
johnsam 2014年

Answers:


345

解决方法:该应用程序不是Web应用程序,因为它在类路径上没有嵌入式容器(例如Tomcat)。加一个固定的。如果您使用的是Maven,则将其添加到pom.xml

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

对于Gradlebuild.gradle),它看起来像

dependencies {
    compile 'org.springframework.boot:spring-boot-starter-web'
}

你是怎样做的 ?
maxime

2
太好了,这就是我所缺少的!
Taobitz

5
我有一个简单的Java应用程序,那么为什么我们需要添加此依赖项?
阿曼库玛(AMAN KUMAR)

请注意,此依赖关系必须是第一个依赖关系。
Cosmin Oprea '18

虽然没有。只是在类路径上。
戴夫·瑟

31

解决方法如下:

  1. 检查您的pom.xml文件中是否不依赖spring-boot-starter-web。为了使您的pom.xml文件正确无误,请使用此链接start.spring.io

  2. 如果您具有上述依赖性,但仍然面临问题,则很有可能存在嵌入式tomcat jar。要确认这一点,请在调试模式下运行maven build-

mvn spring-boot:run --debug

并寻找类似-

[WARNING] error reading /Users/sparrowmac1/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/8.5.20/tomcat-embed-core-8.5.20.jar; invalid LOC header (bad signature) [WARNING] error reading /Users/sparrowmac1/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.8.10/jackson-core-2.8.10.jar; invalid LOC header (bad signature)

如果出现此类消息,请清除本地Maven存储库,然后重试-

mvn dependency:purge-local-repository


一旦缺少所需的jar,dispatcherServlet就不会启动。因此,上述解决方案对我有效。
user3029620

30

我有同样的问题,但是当我删除时

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
</dependency>

它又开始工作了。


添加此tomcat依赖关系后,我的应用程序开始工作。
georgiana_e

1
@georgiana_e删除tomcat依赖项后,我的应用程序开始工作:D发生了什么事?
Daria

:D山姆像我@Daria。
RockOnGom

用Jetty替换了默认的嵌入式容器,以修复该错误。似乎我的Tomcat JAR已损坏,需要进行.m2清除。
CᴴᴀZ

7

也许它不适合您的代码,但我发现您是否有这样的代码片段:

@SpringBootApplication
public class SpringBootApacheKafkaApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootApacheKafkaApplication.class,args).close();
    }
}

然后只需删除close()方法即可。那解决了我的问题!也许我可以帮助某人


3

在我的情况下,当我修复了静态分析错误(没有使用方法的返回值)时,就引入了此问题。

我的Application.java中的旧工作代码是:

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

引入问题的新代码是:

    public static void main(String[] args) {        
      try (ConfigurableApplicationContext context = 
          SpringApplication.run(Application.class, args)) {
        LOG.trace("context: " + context);
      }
    }

显然,try with resource块将在启动应用程序后关闭上下文,这将导致应用程序以状态0退出。在这种情况下,应忽略snarqube静态分析报告的资源泄漏错误。


3

使用gradle,我在依赖关系块中的build.gradle.kts文件处替换了这一行

providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")

有了这个

compile("org.springframework.boot:spring-boot-starter-web")

并且工作正常。



2

另一种可能性,

我更换了

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

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

它开始没有任何问题


1

这项工作与春季启动2.0.0

更换

  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
        </dependency>

<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.6</version>
    </dependency>

1

就我而言,我修复了以下问题:

  1. 首先我删除了(Apache) C:\Users\myuserId\.m2\repository\org\apache

  2. 我在pom.xml文件中添加了以下依赖项

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  3. 我通过在资源文件中添加以下行来更改默认套接字 ..\yourprojectfolder\src\main\resourcesand\application.properties(我手动创建了此文件)

     server.port=8099
     spring.profiles.active=@spring.profiles.active@

    对于我在下面加块pom.xml<build>部分。

      <build>
      .
      .
     <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
       .
       .    
      </build>

我的最终pom.xml文件看起来像

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.bhaiti</groupId>
    <artifactId>spring-boot-rest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-rest</name>
    <description>Welcome project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>

    </build>


</project>

0

如果您不想让Spring成为Web应用程序,则只需将@EnableAsync或添加@EnableScheduling到Starter中

@EnableAsync
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

}

0

就我而言,我已经对'spring-boot-starter-web'具有了maven依赖性,并且当我从IDE中以springboot app的形式运行该项目时,它不会自动停止就可以正常启动。但是,当我将其部署到K8s时,该应用程序将启动并立即自动停止。因此,我修改了主应用程序类以扩展SpringBootServletInitializer,这似乎已解决了自动停止问题。

@SpringBootApplication public class MyApp extends SpringBootServletInitializer {  public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);  }}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.