1
votes

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();
 }

}
1
Should not be a problem. The above implementation should work as is, just remove @Autowired from you constructor.kk.
@KrishnaKuntala That will not work as I don't have a default constructor, so I need Autowired with this constructor.Abhijeet
Got your point. Why do you want to create @Bean in the same class? Could you initialize it in ApplicationInitializer (The class which is annotated as @Configuration) class?kk.

1 Answers

2
votes

@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.