在同一类中创建Bean的Spring Autoire结果为:请求的Bean当前处于创建错误中* [英] Spring Autowire with Bean creation in same class results in :Requested bean is currently in creation Error*

查看:0
本文介绍了在同一类中创建Bean的Spring Autoire结果为:请求的Bean当前处于创建错误中*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个错误是不言而喻的,但是当我将REST模板的设置从构造函数删除到@Autwire@Qualifier("myRestTemplate")私有RestTemplate REST模板时,它起作用了。

我只想知道,如果同一个类具有我试图自动绑定的内容的Bean定义,我如何在构造函数中做到这一点?

org.springframework.beans.factory.BeanCurrentlyInCreationException: 创建名为‘xxx’的Bean时出错:请求的Bean当前在 创建:是否存在无法解析的循环引用?

@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当前正在构造中。

您可以通过设置getRestTemplatestatic来避免此错误。

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

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

这篇关于在同一类中创建Bean的Spring Autoire结果为:请求的Bean当前处于创建错误中*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆