Подтвердить что ты не робот

Почему веб-приложение Spring загружается сразу после запуска?

Используя STS, если я импортирую проект "Rest Service" Начало работы с использованием последней загрузки Spring и выберите "Run As Spring Boot App", он запустится, а затем немедленно выключится.

Глядя на журналы отладки, Spring по какой-то причине решение проекта не является веб-приложением, но я понятия не имею, почему.

Если я переключусь с Spring Boot 1.1.1.RELEASE на 1.0.1.RELEASE, проект будет работать так, как ожидалось, и будет найден встроенный сервер Tomcat по умолчанию.

Я не могу найти что-либо в примечаниях к выпуску 1.1.1, в котором говорится, что есть изменение конфигурации или что-то еще?

UPDATE: шаги для воспроизведения и выхода журнала

Я запускаю STS 3.6.0.M1 и Spring 4.0.5 и Spring Boot 1.1.1. Я могу легко воспроизвести это, выполнив следующие действия:

  • Импорт приложения REST Service Начало работы.
  • Выберите "Запустить как Spring Boot Project"
  • Это результат:

    :: Spring Boot ::        (v1.1.1.RELEASE)
    
    2014-06-14 11:08:34.226  INFO 47728 --- [           main] hello.Application                        : Starting Application on localhost with PID 47728 (/Users/pdrummond/src/sts/gs-rest-service-complete/target/classes started by pdrummond in /Users/pdrummond/src/sts/gs-rest-service-complete)
    2014-06-14 11:08:34.257  INFO 47728 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.spring[email protected]802b249: startup date [Sat Jun 14 11:08:34 BST 2014]; root of context hierarchy
    2014-06-14 11:08:34.680  INFO 47728 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
    2014-06-14 11:08:34.908  INFO 47728 --- [           main] hello.Application                        : Started Application in 0.917 seconds (JVM running for 1.351)
    2014-06-14 11:08:36.397  INFO 47728 --- [       Thread-3] s.c.a.AnnotationConfigApplicationContext : Closing org.spring[email protected]802b249: startup date [Sat Jun 14 11:08:34 BST 2014]; root of context hierarchy
    2014-06-14 11:08:36.398  INFO 47728 --- [       Thread-3] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
    
  • Если я отредактирую pom и измените spring-boot-starter-parent на 1.0.1.RELEASE, он загрузится, как ожидалось.

ОБНОВЛЕНИЕ 2: Добавлен вывод команды --debug

     :: Spring Boot ::        (v1.1.1.RELEASE)

    2014-06-14 19:29:03.814  INFO 986 --- [           main] hello.Application                        : Starting Application on localhost with PID 986 (/Users/pdrummond/src/sts/gs-rest-service-complete/target/classes started by pdrummond in /Users/pdrummond/src/sts/gs-rest-service-complete)
    2014-06-14 19:29:03.816 DEBUG 986 --- [           main] o.s.boot.SpringApplication               : Loading source class hello.Application
    2014-06-14 19:29:03.838  INFO 986 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.spring[email protected]c163956: startup date [Sat Jun 14 19:29:03 BST 2014]; root of context hierarchy
    2014-06-14 19:29:04.177  INFO 986 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
    2014-06-14 19:29:04.346 DEBUG 986 --- [           main] utoConfigurationReportLoggingInitializer : 


    =========================
    AUTO-CONFIGURATION REPORT
    =========================


    Positive matches:
    -----------------

       PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer
          - @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) found no beans (OnBeanCondition)

       JacksonAutoConfiguration
          - @ConditionalOnClass classes found: com.fasterxml.jackson.databind.ObjectMapper (OnClassCondition)

       JacksonAutoConfiguration#jacksonObjectMapper
          - @ConditionalOnMissingBean (types: com.fasterxml.jackson.databind.ObjectMapper; SearchStrategy: all) found no beans (OnBeanCondition)

       JmxAutoConfiguration
          - @ConditionalOnClass classes found: org.springframework.jmx.export.MBeanExporter (OnClassCondition)
          - SpEL expression on org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration: ${spring.jmx.enabled:true} (OnExpressionCondition)

       JmxAutoConfiguration#mbeanServer
          - @ConditionalOnMissingBean (types: javax.management.MBeanServer; SearchStrategy: all) found no beans (OnBeanCondition)

       JmxAutoConfiguration#objectNamingStrategy
          - @ConditionalOnMissingBean (types: org.springframework.jmx.export.naming.ObjectNamingStrategy; SearchStrategy: all) found no beans (OnBeanCondition)

       HttpMessageConvertersAutoConfiguration
          - @ConditionalOnClass classes found: org.springframework.http.converter.HttpMessageConverter (OnClassCondition)

       HttpMessageConvertersAutoConfiguration#messageConverters
          - @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.web.HttpMessageConverters; SearchStrategy: all) found no beans (OnBeanCondition)

       HttpMessageConvertersAutoConfiguration.ObjectMappers
          - @ConditionalOnClass classes found: com.fasterxml.jackson.databind.ObjectMapper (OnClassCondition)

       HttpMessageConvertersAutoConfiguration.ObjectMappers#mappingJackson2HttpMessageConverter
          - @ConditionalOnMissingBean (types: org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; SearchStrategy: all) found no beans (OnBeanCondition)


    Negative matches:
    -----------------

       MessageSourceAutoConfiguration
          - Bundle found for spring.messages.basename: messages (MessageSourceAutoConfiguration.ResourceBundleCondition)

       RabbitAutoConfiguration
          - required @ConditionalOnClass classes not found: org.springframework.amqp.rabbit.core.RabbitTemplate,com.rabbitmq.client.Channel (OnClassCondition)

       AopAutoConfiguration
          - required @ConditionalOnClass classes not found: org.aspectj.lang.annotation.Aspect,org.aspectj.lang.reflect.Advice (OnClassCondition)

       BatchAutoConfiguration
          - required @ConditionalOnClass classes not found: org.springframework.batch.core.launch.JobLauncher,org.springframework.jdbc.core.JdbcOperations (OnClassCondition)

       ElasticsearchRepositoriesAutoConfiguration
          - required @ConditionalOnClass classes not found: org.elasticsearch.client.Client,org.springframework.data.elasticsearch.repository.ElasticsearchRepository (OnClassCondition)

       JpaRepositoriesAutoConfiguration
          - required @ConditionalOnClass classes not found: org.springframework.data.jpa.repository.JpaRepository (OnClassCondition)

       MongoRepositoriesAutoConfiguration
          - required @ConditionalOnClass classes not found: com.mongodb.Mongo,org.springframework.data.mongodb.repository.MongoRepository (OnClassCondition)

       RepositoryRestMvcAutoConfiguration
          - not a web application (OnWebApplicationCondition)

       SolrRepositoriesAutoConfiguration
          - required @ConditionalOnClass classes not found: org.apache.solr.client.solrj.SolrServer,org.springframework.data.solr.repository.SolrRepository (OnClassCondition)

       ElasticsearchAutoConfiguration
          - required @ConditionalOnClass classes not found: org.elasticsearch.client.Client,org.springframework.data.elasticsearch.client.TransportClientFactoryBean,org.springframework.data.elasticsearch.client.NodeClientFactoryBean (OnClassCondition)

       ElasticsearchDataAutoConfiguration
          - required @ConditionalOnClass classes not found: org.elasticsearch.client.Client,org.springframework.data.elasticsearch.core.ElasticsearchTemplate (OnClassCondition)

       FlywayAutoConfiguration
          - required @ConditionalOnClass classes not found: org.flywaydb.core.Flyway (OnClassCondition)

       FreeMarkerAutoConfiguration
          - required @ConditionalOnClass classes not found: freemarker.template.Configuration,org.springframework.ui.freemarker.FreeMarkerConfigurationFactory (OnClassCondition)

       GroovyTemplateAutoConfiguration
          - required @ConditionalOnClass classes not found: groovy.text.TemplateEngine (OnClassCondition)

       HypermediaAutoConfiguration
          - required @ConditionalOnClass classes not found: org.springframework.hateoas.Resource (OnClassCondition)

       IntegrationAutoConfiguration
          - required @ConditionalOnClass classes not found: org.springframework.integration.config.EnableIntegration (OnClassCondition)

       JacksonAutoConfiguration.JodaModuleAutoConfiguration
          - required @ConditionalOnClass classes not found: com.fasterxml.jackson.datatype.joda.JodaModule (OnClassCondition)

       JacksonAutoConfiguration.Jsr310ModuleAutoConfiguration
          - Required JVM version 1.8 or newer found 1.6 (OnJavaCondition)

       DataSourceAutoConfiguration
          - required @ConditionalOnClass classes not found: org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType (OnClassCondition)

       DataSourceTransactionManagerAutoConfiguration
          - required @ConditionalOnClass classes not found: org.springframework.jdbc.core.JdbcTemplate,org.springframework.transaction.PlatformTransactionManager (OnClassCondition)

       JmsAutoConfiguration
          - required @ConditionalOnClass classes not found: org.springframework.jms.core.JmsTemplate (OnClassCondition)

       ActiveMQAutoConfiguration
          - required @ConditionalOnClass classes not found: javax.jms.ConnectionFactory,org.apache.activemq.ActiveMQConnectionFactory (OnClassCondition)

       HornetQAutoConfiguration
          - required @ConditionalOnClass classes not found: javax.jms.ConnectionFactory,org.hornetq.api.jms.HornetQJMSClient (OnClassCondition)

       JmxAutoConfiguration#mbeanExporter
          - @ConditionalOnMissingBean (types: org.springframework.jmx.export.MBeanExporter; SearchStrategy: current) found the following [mbeanExporter] (OnBeanCondition)

       LiquibaseAutoConfiguration
          - required @ConditionalOnClass classes not found: liquibase.integration.spring.SpringLiquibase (OnClassCondition)

       DeviceDelegatingViewResolverAutoConfiguration
          - not a web application (OnWebApplicationCondition)

       DeviceResolverAutoConfiguration
          - required @ConditionalOnClass classes not found: org.springframework.mobile.device.DeviceResolverHandlerInterceptor,org.springframework.mobile.device.DeviceHandlerMethodArgumentResolver (OnClassCondition)

       SitePreferenceAutoConfiguration
          - required @ConditionalOnClass classes not found: org.springframework.mobile.device.site.SitePreferenceHandlerInterceptor,org.springframework.mobile.device.site.SitePreferenceHandlerMethodArgumentResolver (OnClassCondition)

       MongoAutoConfiguration
          - required @ConditionalOnClass classes not found: com.mongodb.Mongo (OnClassCondition)

       MongoDataAutoConfiguration
          - required @ConditionalOnClass classes not found: com.mongodb.Mongo,org.springframework.data.mongodb.core.MongoTemplate (OnClassCondition)

       HibernateJpaAutoConfiguration
          - did not find HibernateEntityManager class (HibernateJpaAutoConfiguration.HibernateEntityManagerCondition)

       ReactorAutoConfiguration
          - required @ConditionalOnClass classes not found: reactor.spring.context.config.EnableReactor (OnClassCondition)

       RedisAutoConfiguration
          - required @ConditionalOnClass classes not found: org.springframework.data.redis.connection.jedis.JedisConnection,org.springframework.data.redis.core.RedisOperations,redis.clients.jedis.Jedis (OnClassCondition)

       FallbackWebSecurityAutoConfiguration
          - SpEL expression on org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration: !${security.basic.enabled:true} (OnExpressionCondition)

       SecurityAutoConfiguration
          - required @ConditionalOnClass classes not found: org.springframework.security.authentication.AuthenticationManager (OnClassCondition)

       FacebookAutoConfiguration
          - required @ConditionalOnClass classes not found: org.springframework.social.facebook.connect.FacebookConnectionFactory (OnClassCondition)

       LinkedInAutoConfiguration
          - required @ConditionalOnClass classes not found: org.springframework.social.linkedin.connect.LinkedInConnectionFactory (OnClassCondition)

       SocialWebAutoConfiguration
          - required @ConditionalOnClass classes not found: org.springframework.social.connect.web.ConnectController,org.springframework.social.config.annotation.SocialConfigurerAdapter (OnClassCondition)

       TwitterAutoConfiguration
          - required @ConditionalOnClass classes not found: org.springframework.social.twitter.connect.TwitterConnectionFactory (OnClassCondition)

       SolrAutoConfiguration
          - required @ConditionalOnClass classes not found: org.apache.solr.client.solrj.SolrServer (OnClassCondition)

       ThymeleafAutoConfiguration
          - required @ConditionalOnClass classes not found: org.thymeleaf.spring4.SpringTemplateEngine (OnClassCondition)

       VelocityAutoConfiguration
          - required @ConditionalOnClass classes not found: org.apache.velocity.app.VelocityEngine,org.springframework.ui.velocity.VelocityEngineFactory (OnClassCondition)

       DispatcherServletAutoConfiguration
          - not a web application (OnWebApplicationCondition)

       EmbeddedServletContainerAutoConfiguration
          - not a web application (OnWebApplicationCondition)

       ErrorMvcAutoConfiguration
          - required @ConditionalOnClass classes not found: javax.servlet.Servlet,org.springframework.web.servlet.DispatcherServlet (OnClassCondition)

       MultipartAutoConfiguration
          - required @ConditionalOnClass classes not found: javax.servlet.Servlet,javax.servlet.MultipartConfigElement (OnClassCondition)

       ServerPropertiesAutoConfiguration
          - not a web application (OnWebApplicationCondition)

       WebMvcAutoConfiguration
          - not a web application (OnWebApplicationCondition)

       WebSocketAutoConfiguration
          - required @ConditionalOnClass classes not found: javax.servlet.Servlet,org.apache.catalina.startup.Tomcat,org.springframework.web.socket.WebSocketHandler,org.apache.tomcat.websocket.server.WsSci (OnClassCondition)



    2014-06-14 19:29:04.348  INFO 986 --- [           main] hello.Application                        : Started Application in 0.73 seconds (JVM running for 1.085)
    2014-06-14 19:29:06.378  INFO 986 --- [       Thread-3] s.c.a.AnnotationConfigApplicationContext : Closing org.spring[email protected]c163956: startup date [Sat Jun 14 19:29:03 BST 2014]; root of context hierarchy
    2014-06-14 19:29:06.379  INFO 986 --- [       Thread-3] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
4b9b3361

Ответ 1

У меня была такая же проблема. Чтобы он работал, мне пришлось настроить pom.xml и прокомментировать "предоставленную" область для артефакта spring -boot-starter-tomcat и обновить зависимости.

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

Теперь он запускается, как ожидалось! Благодаря некоторым другим ответам, которые поставили меня на правильный путь.

Ответ 2

Проверьте журнал mvn, когда вы выполняете фазу пакета, и убедитесь, что ящик tomcat-embed-core назначен в jar приложения.

Ответ 3

У меня была такая же проблема, когда мое приложение spring -boot немедленно отключилось без каких-либо следов запуска tomcat, хотя у меня была зависимость <artifactId>spring-boot-starter-web</artifactId>, включенная в мой pom.xml. Это означает, что spring -boot не распознает мое приложение как веб-приложение.

Попробовал очистить и снова упаковать мое приложение, используя утилиты mvn clean install, чтобы проверить, будут ли библиотеки tomcat упаковываться в мое приложение binary/deployable. Нашел следующую проблему:

[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ exam-launcher ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 2 source files to C:\XXXXX\XXXXXX\XXXX_Workspace\my-app\target\classes
[WARNING] error reading c:\.m2\org\apache\tomcat\embed\tomcat-embed-core\8.5.14\tomcat-embed-core-8.5.14.jar; invalid LOC header (bad signature)
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ exam-launcher ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory C:\Chaithu\Work_Related\Eclipse_Neon_Workspace\exam-portal-server\src\test\resources

Библиотека tomcat, которая была у меня на моем локальном репо, повреждена (по неизвестным причинам), из-за которой она не включалась в пакет maven. Удалите соответствующую папку из моего локального репозитория maven и позвольте maven загружать его только что. И теперь это работает как шарм!

Ответ 4

Я нашел причину этого. Моей было то, что я не включил ни одну библиотеку, которая приносит с ней время работы tomcat. Я включил зависимость spring -web и spring -boot-starter-data-jpa (показано ниже), но ни один из этих пакетов не приведет к тому, что время выполнения tomcat для этого приложения будет запущено. Таким образом, это было автоматическое выключение.

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

Решение заключалось в том, чтобы изменить spring -web на spring -boot-starter-web (показано ниже). В эту библиотеку входит библиотека tomcat, и мое приложение запустилось.

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

Ответ 5

Просто добавьте

 spring.main.web-environment=true

в application.properties и перезапустите.

Ответ 6

Кроме того, вы должны проверить, что в вашем приложении есть хотя бы один контроллер для отдыха (@RestController) и убедитесь, что вы скомпилируете его с помощью spring-boot-starter-tomcat

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

Ответ 7

У меня была такая же проблема, и я потратил некоторое время на поиск решения. Я знаю, что вопрос уже несколько лет, но это может спасти кого-то еще в будущем.

Я получил это предупреждение, когда я запустил mvn clean install:

[WARNING] error reading /Users/fotouhm/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/8.5.16/tomcat-embed-core-8.5.16.jar; zip file is empty

По какой-то причине этот файл поврежден. Просто перейдите по ссылке ниже и замените ее.

http://central.maven.org/maven2/org/apache/tomcat/embed/tomcat-embed-core/8.5.16/tomcat-embed-core-8.5.16.jar