【问题标题】:Circular dependencies error in Spring when using self autowiring feature使用自自动装配功能时 Spring 中的循环依赖错误
【发布时间】:2018-10-18 22:05:00
【问题描述】:

我正在使用带有此代码的 Spring Boot 版本 1.5.10.RELEASE(最新版本之一):

@Service
public class AService {

private AService aService; //Self autowire

public AService(AService aService){
    this.aService = aService;
}

@Cacheable(value = "aCacheName")
public List<SomeClass> expensiveOperation(){
    //Very expensive operation that can be cached
}

public List<SomeClass> otherOperation(){
    return aService.expensiveOperation().otherOperation()); //Call proxy, can't use this.expensiveOperation() because it will bypass the cache
}
}

我收到此错误:

“应用上下文中一些bean的依赖形成了一个循环。”

我知道 Spring 允许“自我自动装配”,我做错了什么?

谢谢。

【问题讨论】:

    标签: spring spring-boot ioc-container


    【解决方案1】:

    this 有什么问题??您也可以将其标记为 @Lazy 并使用字段 autowire 或使用 setter 代替构造函数。您将无法使用构造函数恕我直言,因为您将永远无法提供构造实例。

    【讨论】:

    • 如果你调用“this”,它会再次运行昂贵的Operation(),在@Cacheable下。
    • 您可以随时注入应用程序上下文并获取和获取您的 bean。您甚至可以在 @PostConstruct 中进行分配,因为此时所有 bean 都应该是可注入的。
    猜你喜欢
    • 1970-01-01
    • 2016-02-03
    • 2013-05-03
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 2014-08-17
    相关资源
    最近更新 更多