不鼓励依赖循环引用,并且默认情况下在 Spring Boot 应用程序中禁止使用循环引用

pri*_*nha 17 spring-boot

当我运行 Spring Boot 应用程序时,出现以下错误消息。

\n
Description:\n\nThe dependencies of some of the beans in the application context form a cycle:\n\n\xe2\x94\x8c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x90\n|  securityConfiguration (field private com.prity.springbootdemo1.service.UserService com.prity.springbootdemo1.config.SecurityConfiguration.userService)\n\xe2\x86\x91     \xe2\x86\x93\n|  userServiceImpl (field private org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder com.prity.springbootdemo1.service.UserServiceImpl.passwordEncoder)\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x98\n\n\nAction:\n\nRelying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.\n
Run Code Online (Sandbox Code Playgroud)\n

Dom*_*tko 13

你可以尝试用这个。将其添加到文件application.properties

spring.main.allow-circular-references=true
Run Code Online (Sandbox Code Playgroud)

并尝试奔跑。这不是最好的解决方案,您仍然需要找到更好的方法来解决问题


小智 11

因此,如果您有一个类A,并且在将类注入A到 class 的构造函数中时遇到此问题B,请@Lazy在 class 的构造函数中使用注释B。这将打破循环并将 的 beanA懒惰地注入到B. 因此,它不会完全初始化 bean,而是创建一个代理来注入另一个 bean。注入的 bean 仅在第一次需要时才会完全创建。

@Component
public class CircularDependencyA {

    private CircularDependencyB circB;

    @Autowired
    public CircularDependencyA(@Lazy CircularDependencyB circB) {
        this.circB = circB;
    }
}
Run Code Online (Sandbox Code Playgroud)