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

sme*_*eeb 2 groovy spring spring-boot

我在 GitHub 上创建了一个spring-boot-troubleshooting 存储库,可以准确地重现此错误。

我正在构建一个基于 Spring Boot 的 REST 服务,但很难让启动侦听器正常工作:

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

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

当我运行应用程序时:

./gradlew build && java -Dspring.config=. -jar build/libs/spring-boot-troubleshooting.jar
Run Code Online (Sandbox Code Playgroud)

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

pvp*_*ran 5

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