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的循环依赖问题

 

posted @ 2022-12-02 15:32  唏嘘-  阅读(830)  评论(0编辑  收藏  举报