gpt4 book ai didi

java - Spring Autowire 在同一类中创建 Bean 结果为 :Requested bean is currently in creation Error*

转载 作者:行者123 更新时间:2023-12-02 12:47:22 26 4
gpt4 key购买 nike

我知道这个错误是不言自明的,但是当我将其余模板的设置从构造函数删除到 @Autowired @Qualifier("myRestTemplate") private RestTemplate restTemplate 时,它​​就可以工作了。

只是想知道如果同一个类具有我尝试 Autowiring 的 bean 定义,我该如何在构造函数中执行此操作?

org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'xxx': Requested bean is currently in creation: Is there an unresolvable circular reference?

@Component
public class xxx {

private RestTemplate restTemplate;

@Autowired
public xxx(@Qualifier("myRestTemplate") RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}

@Bean(name="myRestTemplate")
public RestTemplate getRestTemplate() {
return new RestTemplate();
}

}

最佳答案

@Bean常规 @Component 注解类中的方法以所谓的 精简模式 进行处理。

我不知道你为什么要这样做。如果您的 xxx 类控制 RestTemplate 的实例化,则没有太多理由不在构造函数中自行执行此操作(除非您打算将其公开给上下文的其余部分) ,但还有更好的解决方案)。

无论如何,Spring 要调用您的 getRestTemplate 工厂方法,它需要一个 xxx 实例。要创建 xxx 的实例,它需要调用其构造函数,该构造函数需要一个 RestTemplate,但您的 RestTemplate 当前正在构造中。

您可以通过将 getRestTemplate 设置为 static 来避免此错误。

@Bean(name="myRestTemplate")
public static RestTemplate getRestTemplate() {
return new RestTemplate();
}

在这种情况下,Spring 不需要 xxx 实例来调用 getRestTemplate 工厂方法。

关于java - Spring Autowire 在同一类中创建 Bean 结果为 :Requested bean is currently in creation Error*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44710912/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com