简体   繁体   English

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

[英]Why does my Spring Boot App always shutdown immediately after starting?

This is my first Spring Boot code.这是我的第一个 Spring 引导代码。 Unfortunately, it always shuts down.不幸的是,它总是关闭。 I was expecting it to run continuously so that my web client can get some data from the browser.我期待它持续运行,以便我的 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

Please advise.请指教。

Thanks谢谢

PS build.gradle is the fault. PS build.gradle 是故障。

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

Once I took off the above line in bold, everything works.一旦我以粗体形式取消了上述行,一切正常。 My application context now is correct.我的应用程序上下文现在是正确的。 Thanks Dave谢谢戴夫

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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]]

Resolution: the app is not a webapp because it doesn't have an embedded container (eg Tomcat) on the classpath.解决方案:该应用程序不是 Web 应用程序,因为它在类路径上没有嵌入式容器(例如 Tomcat)。 Adding one fixed it.添加一个修复它。 If you are using Maven , then add this in pom.xml :如果您使用的是Maven ,则在pom.xml添加:

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

For Gradle ( build.gradle ) it looks like对于Gradle ( build.gradle ),它看起来像

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

Here is how you can fix it:以下是修复它的方法:

  1. Check if you don't have dependency on spring-boot-starter-web in your pom.xml file.检查您的 pom.xml 文件中是否不依赖 spring-boot-starter-web。 To get you pom.xml file right, use this link start.spring.io为了让你 pom.xml 文件正确,使用这个链接start.spring.io

  2. If you have above dependency, but still facing the issue, it is highly possible that your embedded tomcat jars are present.如果您具有上述依赖性,但仍然面临问题,则很可能存在您的嵌入式 tomcat jar。 To confirm this, run maven build in debug mode -要确认这一点,请在调试模式下运行 maven build -

mvn spring-boot:run --debug

and look for messages like -并寻找类似的消息 -

[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)

If such messages are present, purge your local maven repo and try again -如果存在此类消息,请清除您的本地 Maven 存储库并重试 -

mvn dependency:purge-local-repository

I had the same problem but when I removed我有同样的问题,但是当我删除时

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

it started working again.它又开始工作了。

Maybe it does not fit to your code but i found out if you have a code snippet like this:也许它不适合您的代码,但我发现您是否有这样的代码片段:

@SpringBootApplication
public class SpringBootApacheKafkaApplication {

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

then just remove the close() method.然后只需删除 close() 方法。 That's fixed my problem!这解决了我的问题! Maybe I can help someone with that也许我可以帮助某人

In my case the problem was introduced when I fixed a static analysis error that the return value of a method was not used.在我的情况下,当我修复未使用方法的返回值的静态分析错误时引入了问题。

Old working code in my Application.java was:我的 Application.java 中的旧工作代码是:

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

New code that introduced the problem was:引入问题的新代码是:

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

Obviously, the try with resource block will close the context after starting the application which will result in the application exiting with status 0. This was a case where the resource leak error reported by snarqube static analysis should be ignored.显然,try with resource 块会在启动应用程序后关闭上下文,这将导致应用程序以状态 0 退出。 这是一种应该忽略 snarqube 静态分析报告的资源泄漏错误的情况。

With gradle, I replaced this line at build.gradle.kts file inside dependencies block使用 gradle,我在依赖块内的 build.gradle.kts 文件中替换了这一行

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

with this有了这个

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

and works fine.并且工作正常。

I think the right answer was at Why does Spring Boot web app close immediately after starting?我认为正确的答案是为什么 Spring Boot web 应用程序启动后立即关闭? about the starter-tomcat not being set and if set and running through the IDE, the provided scope should be commented off.关于未设置 starter-tomcat,如果设置并通过 IDE 运行,则应注释掉提供的范围。 Scope doesn't create an issue while running through command. Scope 在通过命令运行时不会产生问题。 I wonder why.我想知道为什么。

Anyways just added my additional thoughts.无论如何只是添加了我的其他想法。

Just another possibility,只是另一种可能,

I replaced我换了

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

with

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

and it started without any issues它开始没有任何问题

我的应用程序是 Spring Boot 批处理,在 application.properties 中的以下行注释解决了问题

spring.main.web-application-type=none

this work with spring boot 2.0.0这项工作与弹簧靴 2.0.0

replace代替

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

with

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

In my case I fixed this issue like below:-就我而言,我解决了这个问题,如下所示:-

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

  2. I added below dependencies in my pom.xml file我在pom.xml文件中添加了以下依赖项

    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
  3. I have changed the default socket by adding below lines in resource file ..\\yourprojectfolder\\src\\main\\resourcesand\\application.properties (I manually created this file)我通过在资源文件..\\yourprojectfolder\\src\\main\\resourcesand\\application.properties添加以下行来更改默认套接字(我手动创建了这个文件)

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

    for that I have added below block in my pom.xml under <build> section.为此,我在<build>部分下的pom.xml添加了以下块。

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

My final pom.xml file look like我最终的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>

If you don't want to make your spring a web application then just add @EnableAsync or @EnableScheduling to your Starter如果您不想让 Spring 成为 Web 应用程序,那么只需将@EnableAsync@EnableScheduling添加到您的 Starter

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

}

I went through the answers here and elsewhere and still had issues.我浏览了这里和其他地方的答案,但仍然有问题。 It turned that (like the op), I was running in kubernetes, and the app was fine, but kubernetes had an issue.结果是(就像操作一样),我在 kubernetes 中运行,并且应用程序很好,但是 kubernetes 有问题。

I forgot to have my app start based on my port environment variable.我忘记根据我的端口环境变量启动我的应用程序。 So, kubernetes/helm was telling it to run on 8443 and to liveness probe that, but it was running on some other port (like 8123) from my application.properties.因此,kubernetes/helm 告诉它在 8443 上运行并对其进行活性探测,但它正在我的 application.properties 中的其他端口(如 8123)上运行。

The kubernetes events (get events) showed the live-ness probe was failing, so kubernetes was killing the pod/app every 30 seconds or so. kubernetes 事件(get 事件)显示 live-ness 探测失败,因此 kubernetes 每 30 秒左右杀死一次 pod/app。

If you have a circular spring injected dependency it will fail without warning, depending on the level of logging, and a few other factors.如果您有一个圆形弹簧注入依赖项,它将在没有警告的情况下失败,具体取决于日志记录级别和其他一些因素。

Class A injects Class B, and Class B injects Class A. Via constructor, in this particular case.在这种特殊情况下,A 类注入 B 类,B 类注入 A 类。通过构造函数。

in my case i already had the maven dependency to 'spring-boot-starter-web' and the project would start fine without auto-stopping when i run it as springboot app from within the IDE .在我的情况下,我已经拥有对“spring-boot-starter-web”的 maven 依赖,当我从 IDE 中将它作为 springboot 应用程序运行时,该项目将正常启动而不会自动停止。 however, when i deploy it to K8s , the app would start and auto-stop immediately.但是,当我将它部署到K8s 时,该应用程序会立即启动并自动停止。 So i modified my main app class to extend SpringBootServletInitializer and this seems to have fixed the auto-stopping.所以我修改了我的主应用程序类来扩展 SpringBootServletInitializer,这似乎修复了自动停止。

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

I was having a similar problem.我遇到了类似的问题。 I only had the following starter web package.我只有以下入门 web 包。

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

But it is not enough.但这还不够。 You need to add a parent too to get other required dependencies.您还需要添加一个父级以获取其他所需的依赖项。

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

I initialized a new SPring boot project in IntelliJIdea with Spring Boot dev tools, but in pom.xml I had only dependency我使用 Spring Boot 开发工具在 IntelliJIdea 中初始化了一个新的 SPring 启动项目,但在 pom.xml 中我只有依赖项

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

You need to have also artifact spring-boot-starter-web .你还需要有神器spring-boot-starter-web Just add this dependency to pom.xml只需将此依赖项添加到 pom.xml

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

I had this problem, and in my case it was caused by a simple clumsy mistake: my class had:我遇到了这个问题,就我而言,它是由一个简单的笨拙错误引起的:我的班级有:

@SpringBootApplication
public class MyApplication implements ApplicationRunner {

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

public void run(ApplicationArguments args) throws Exception {

}

} }

I removed the "implements ApplicationRunner" and the run method (which were there due to a copy-paste mistake) and then it worked我删除了“implements ApplicationRunner”和 run 方法(由于复制粘贴错误而存在),然后它起作用了

删除 Maven m2 文件夹(在 linux ~/.m2 上)并重建应用程序

If you are using Java 9 JPMS it is not enough to add spring-boot-starter-web as a dependency, as tomcat-embed lib would not be available at runtime and spring boot will not detect the app as web app.如果您使用的是 Java 9 JPMS,将 spring-boot-starter-web 添加为依赖项是不够的,因为 tomcat-embed 库在运行时不可用,并且 spring boot 不会将该应用程序检测为 Web 应用程序。

To fix this make tomcat embed available via following directive added to your module-info.java for main app要解决此问题,通过添加到主应用程序的module-info.java 中的以下指令使 tomcat embed 可用

 requires org.apache.tomcat.embed.core;
 

In my case, the problem happened when I tried to insert 5000 records into database (it worked okay with fewer records)就我而言,当我尝试将 5000 条记录插入数据库时发生了问题(它可以在较少记录的情况下正常工作)
What worked for me: Uncomment devtools dependency in pom.xml file:什么对我有用:取消注释 pom.xml 文件中的 devtools 依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>

Here is how you can fix it:以下是您可以解决的方法:

Check if you don't have dependency on spring-boot-starter-web in your pom.xml file.检查您的 pom.xml 文件中是否不依赖 spring-boot-starter-web。 To get you pom.xml file right, use this link start.spring.io要获得 pom.xml 文件,请使用此链接 start.spring.io

If you have above dependency, but still facing the issue, it is highly possible that your embedded tomcat jars are present.如果您有上述依赖性,但仍面临问题,则很有可能您的嵌入式 tomcat jars 存在。 To confirm this, run maven build in debug mode -要确认这一点,请在调试模式下运行 maven build -

mvn spring-boot:run --debug

if you want to see detail logs then you can run it with debug on using below command如果您想查看详细日志,则可以使用以下命令通过调试运行它

 java  -Ddebug -jar .\app.jar

For me it was due to below exception对我来说,这是由于以下异常

 org.apache.logging.log4j.core.appender.AppenderLoggingException: java.lang.NoSuchMethodError: org.apache.logging.log4j.util.StackLocatorUtil.getCurrentStackTrace()Ljava/ut

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM