專案啟動報錯怎麼辦?看看你Spring自動注入用對了嘛?@Autowired XxxService注入問題解決

攻城獅Chova發表於2022-01-01

問題

  • Controller層使用 @Autowired注入Service時,提示Bean中沒有Service
  • Service介面中使用 @Component注入後,啟動專案問題提示:
The web application [ROOT] appears to have started a thread named [DubboClientReconnectTimer-thread-2] but has failed to stop it.
This is very likely to create a memory leak

原因

  • 提示Bean中沒有Service:
    • 因為沒有將Service注入到Spring容器中,可以通過 @Component或者 @Service註解注入
  • 在Service中使用註解注入到容器後,啟動專案會報錯:
    • 因為在Service介面注入,同時注入了兩個Bean
    • 在Service介面注入,會將實現Service介面的子類也注入到容器中,所以會導致Dubbo重複性執行緒錯誤

解決辦法

  • Service的實現類ServiceImpl上,使用 @Component或者 @Service註解將Service注入到Spring容器中
  • 如果是使用Dubbo的SpringBoot專案,可以在Service實現類使用如下註解
@com.alibaba.dubbo.config.annotation.Service
@org.springframework.stereotype.Service
  • 注意: 要將Service實現類注入到容器,而不是Service介面

總結

  • Spring容器注入規則

相關文章