Java 在同一类中创建Bean的Spring Autowire导致:请求的Bean当前处于创建错误状态*

Java 在同一类中创建Bean的Spring Autowire导致:请求的Bean当前处于创建错误状态*,java,spring,autowired,Java,Spring,Autowired,我知道这个错误是不言自明的,但当我将rest模板的设置从构造函数中移除为@Autowired@Qualifier(“myRestTemplate”)私有RestTemplate RestTemplate时,它就起作用了 我只是想知道,如果同一个类有我试图自动连接的bean定义,我如何在构造函数中实现这一点 org.springframework.beans.factory.beancurrentlyIncrementationException: 创建名为“xxx”的bean时出错:请求的bea

我知道这个错误是不言自明的,但当我将rest模板的设置从构造函数中移除为@Autowired@Qualifier(“myRestTemplate”)私有RestTemplate RestTemplate时,它就起作用了

我只是想知道,如果同一个类有我试图自动连接的bean定义,我如何在构造函数中实现这一点

org.springframework.beans.factory.beancurrentlyIncrementationException: 创建名为“xxx”的bean时出错:请求的bean当前处于 创建:是否存在无法解析的循环引用

常规
@Component
注释类中的方法以称为lite模式的方式处理

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

在任何情况下,为了让Spring调用您的
getRestTemplate
factory方法,它需要一个
xxx
的实例。要创建
xxx
的实例,它需要调用其构造函数,该构造函数需要一个
restemplate
,但您的
restemplate
当前正在构造中

您可以通过使
getrestemplate
static
来避免此错误

@Bean(name="myRestTemplate")
public static RestTemplate getRestTemplate() {
    return new RestTemplate();
}
在这种情况下,Spring不需要一个
xxx
实例来调用
getRestTemplate
工厂方法。

常规
@Component
注释类中的方法是以所谓的lite模式处理的

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

在任何情况下,为了让Spring调用您的
getRestTemplate
factory方法,它需要一个
xxx
的实例。要创建
xxx
的实例,它需要调用其构造函数,该构造函数需要一个
restemplate
,但您的
restemplate
当前正在构造中

您可以通过使
getrestemplate
static
来避免此错误

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

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

应该不是问题。上述实现应按原样工作,只需从构造函数中删除
@Autowired
。@KrishnaKuntala这将不起作用,因为我没有默认构造函数,所以我需要使用此构造函数进行自动连接。明白了。为什么要在同一个类中创建
@Bean
?您能在
ApplicationInitializer
(注释为
@Configuration
)类中初始化它吗?应该不会有问题。上述实现应按原样工作,只需从构造函数中删除
@Autowired
。@KrishnaKuntala这将不起作用,因为我没有默认构造函数,所以我需要使用此构造函数进行自动连接。明白了。为什么要在同一个类中创建
@Bean
?你能在
ApplicationInitializer
(被注释为
@Configuration
)类中初始化它吗?是的,“但是还有更好的解决方案”促使我在@Configuration中移动Bean创建,现在它工作得很好,非常感谢。是的,“但是还有更好的解决方案”驱动我在@configuration中移动Bean创建,现在它工作正常,非常感谢。