¿Por qué mi aplicación Spring Boot siempre se apaga inmediatamente después de comenzar?


Este es mi primer código de arranque de primavera. Desafortunadamente, siempre se apaga. Esperaba que se ejecutara continuamente para que mi cliente web pueda obtener algunos datos del navegador.

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

Por favor avise.

Gracias

P.d. construir.gradle es la culpa.

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

Una vez que me quité la línea anterior en negrita, todo funciona. Mi contexto de aplicación ahora es correcto. Gracias 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]]
Author: Adam, 2014-03-13

9 answers

Resolución: la aplicación no es una aplicación web porque no tiene un contenedor incrustado (por ejemplo, Tomcat) en la ruta de clase. Agregar uno lo arregló. Si estás usando Maven, entonces agrega esto en pom.xml:

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

Para Gradle (build.gradle) parece que

dependencies {
    compile 'org.springframework.boot:spring-boot-starter-web'
}
 219
Author: Dave Syer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-27 18:47:07

Así es como puedes arreglarlo:

  1. Compruebe si no tiene dependencia de spring-boot-starter-web en su pom.archivo xml. Para conseguirte pom.archivo xml correcto, utilice este enlace start.spring.io

  2. Si tiene una dependencia anterior, pero aún enfrenta el problema, es muy posible que sus tarros tomcat incrustados estén presentes. Para confirmar esto, ejecute maven build en modo de depuración -

mvn spring-boot:run --debug

Y busca mensajes como -

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

Si tales mensajes están presentes, purgue su repositorio maven local e inténtelo de nuevo -

mvn dependency:purge-local-repository

 25
Author: chatsap,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-18 09:19:46

Tuve el mismo problema pero cuando eliminé

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

Comenzó a funcionar de nuevo.

 16
Author: N. berouain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-30 13:05:42

En mi caso, el problema se introdujo cuando arreglé un error de análisis estático que el valor devuelto de un método no se usaba.

Código de trabajo antiguo en mi Aplicación.java era:

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

El nuevo código que introdujo el problema fue:

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

Obviamente, el bloque try with resource cerrará el contexto después de iniciar la aplicación, lo que resultará en que la aplicación salga con el estado 0. Este fue un caso en el que el error de fuga de recursos reportado por snarqube static el análisis debe ser ignorado.

 2
Author: Farrukh Najmi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-17 11:59:45

Creo que la respuesta correcta estaba en ¿Por qué Spring Boot web app se cierra inmediatamente después de comenzar? acerca de que el starter-tomcat no está configurado y si se establece y se ejecuta a través del IDE, el ámbito proporcionado debe ser comentado. El ámbito no crea un problema mientras se ejecuta a través del comando. Me pregunto por qué.

De todos modos acabo de añadir mis pensamientos adicionales.

 1
Author: Ajay Menon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:21

Tal vez no se ajuste a su código, pero descubrí si tiene un fragmento de código como este:

@SpringBootApplication
public class SpringBootApacheKafkaApplication {

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

Luego simplemente elimina el método close (). ¡Eso solucionó mi problema! Tal vez pueda ayudar a alguien con eso

 0
Author: DrMed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-14 18:51:16

Esto funciona con spring boot 2.0.0

Sustitúyase

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

Con

<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.6</version>
    </dependency>
 0
Author: RAUL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-19 21:52:16

En mi caso he solucionado este problema como a continuación: -

  1. Primero eliminé (apache) C:\Users\myuserId\.m2\repository\org\apache

  2. He añadido a continuación dependencias en mi archivo pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
  3. He cambiado el socket por defecto añadiendo las siguientes líneas en el archivo de recursos ..\yourprojectfolder\src\main\resourcesand\application.properties (he creado manualmente este archivo)

     server.port=8099
     [email protected]@
    

    Para eso he añadido debajo del bloque en mi pom.xml bajo <build> sección.

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

Mi archivo final pom.xml se parece a

<?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
Author: Abhijit Pritam Dutta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-22 11:42:19

Solo otra posibilidad,

Sustituí

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

Con

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

Y comenzó sin ningún problema

 0
Author: Mohammed Rafeeq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-20 08:58:40