Spring Boot ApplicationListener 在应用程序启动时未运行

标签 spring spring-boot groovy

我创建了一个spring-boot-troubleshooting repo on GitHub准确地重现了这个错误。

我正在构建基于 Spring Boot 的 REST 服务,但很难获得 startup listener上类:

@Slf4j
class StartupListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    ScheduledReporter metricReporter

    @Override
    void onApplicationEvent(ContextRefreshedEvent event) {
        log.info('StartupListener is starting...')
        metricReporter.start(1, TimeUnit.SECONDS)
    }
}

当我运行应用程序时:

./gradlew build && java -Dspring.config=. -jar build/libs/spring-boot-troubleshooting.jar

一切都会启动,没有错误/异常,但是我从未看到我的“StartupListener 正在启动...”日志消息打印到控制台。这告诉我Spring没有启动我的StartupListener。有什么想法可以解决吗?

最佳答案

这个类不是spring bean(我也查看了repo中的文件),所以spring根本没有扫描这个。因此这永远不会被调用。
尝试为此类添加 @Component

关于Spring Boot ApplicationListener 在应用程序启动时未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48007416/

相关文章:

java - Spring MVC Controller 与属性文件的映射

spring-mvc - 如何使用Spring MVC @RequestParam解析不同的ISO日期/时间格式

spring-mvc - Spring引导无法访问ClientHttpRequestInterceptor中的@Value

gradle - Groovy覆盖默认调用方法

java - 使用 java spring 中的 Post-Redirect-Get 模式转换 Post 请求

java - Spring声明式事务模式下事务似乎不起作用

java - @Pathvariable 的 UrlMapping 通配符

spring-boot - 出于安全原因升级 netty 及其组件的正确方法是什么?

gradle - Gradle的Groovy语法:项目

gradle - 无法加载类 grails.plugins.rendering.image.ImageRenderingService Grails 4 渲染 :2. 03