Abh*_*eet 2 java spring autowired
我知道该错误是不言自明的,但是当我将其余模板的设置从构造函数删除为 @Autowired @Qualifier("myRestTemplate") private RestTemplate restTemplate 时,它起作用了。
只是想知道如果同一个类具有我要自动装配的 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();
}
}
Run Code Online (Sandbox Code Playgroud)
@Bean常规@Component带注释的类中的方法以所谓的精简模式进行处理。
我不知道你为什么要这样做。如果您的xxx类控制 的实例化RestTemplate,则没有太多理由不在构造函数中自己执行此操作(除非您打算将其公开给上下文的其余部分,但还有更好的解决方案)。
无论如何,为了让 Spring 调用你的getRestTemplate工厂方法,它需要一个xxx. 要创建 的实例xxx,它需要调用其构造函数,该构造函数需要 a RestTemplate,但您RestTemplate当前正在构造中。
您可以通过制作来避免此错误getRestTemplate static。
@Bean(name="myRestTemplate")
public static RestTemplate getRestTemplate() {
return new RestTemplate();
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,Spring 不需要xxx实例来调用getRestTemplate工厂方法。
| 归档时间: |
|
| 查看次数: |
10474 次 |
| 最近记录: |