1. 程式人生 > 其它 >The dependencies of some of the beans in the application context form a cycle

The dependencies of some of the beans in the application context form a cycle

報錯日誌:

Description:
The dependencies of some of the beans in the application context form a cycle:
   personController (field com.example.wongz.service.UserService com.example.wongz.controller.PersonController.userService)
┌─────┐
|  UserServiceImplName (field com.example.wongz.service.impl.PersonService com.example.wongz.service.impl.UserServiceImpl.personService)
↑     ↓
| personService (field private com.example.wongz.service.UserService com.example.wongz.service.impl.PersonService.userService) └─────┘

報錯原因:

兩個類相互引用對方,導致Spring在初始化bean的時候不知道先初始化哪個,從而形成迴圈依賴注入。

解決方法:

1、其中一個不要引用對方,避免迴圈依賴

2、任選其中一個使用@Lazy 註解。

Spring在應用程式上下文啟動時去建立所有的單例bean物件, 而@Lazy註解可以延遲載入bean物件,即在使用時才去初始化.

所以,@Lazy註解, 一是可以減少Spring的IOC容器啟動時的載入時間, 二是可以解決bean的迴圈依賴問題