我创建了一个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/