Java – Spring Autowire with Bean creation in same class results in :Requested bean is currently in creation Error*

autowiredjavaspring

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 the RestTemplate, 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 of xxx. To create an instance of xxx, it needs to invoke its constructor which expects a RestTemplate, but your RestTemplate is currently in construction.

You can avoid this error by making getRestTemplate static.

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

In this case, Spring doesn't need an xxx instance to invoke the getRestTemplate factory method.

Related Topic