I know the error is self explanatory, but when I remove the setting of rest template from constructor to @Autowired @Qualifier("myRestTemplate") private RestTemplate restTemplate, it works.
Just want to know how can I do that in constructor if the same class has bean definition of what I am trying to autowire?
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();
}
}
Best Answer
@Bean
methods in a regular@Component
annotated class are processed in what is known as lite-mode.I don't know why you'd want to do this. If your
xxx
class controls the instantiation of theRestTemplate
, there's not much reason not to do it yourself in the constructor (unless you mean to expose it to the rest of the context, but then there are better solutions).In any case, for Spring to invoke your
getRestTemplate
factory method, it needs an instance ofxxx
. To create an instance ofxxx
, it needs to invoke its constructor which expects aRestTemplate
, but yourRestTemplate
is currently in construction.You can avoid this error by making
getRestTemplate
static
.In this case, Spring doesn't need an
xxx
instance to invoke thegetRestTemplate
factory method.