Search code examples
javaspringjavabeansspring-cloud

@RefreshScope can't get along with @Bean


I have a controller which need refresh config from config server so I add @RefreshScope on it. Meanwhile this controller need to calling a backend API so that I defined the restTemplate Bean. But once I start this application, exception occur. Can anyone tell me why these two annotation make circulate reference?

Error: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'scopedTarget.frontEndApplication': 
Unsatisfied dependency expressed through field 'restTemplate'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'restTemplate': Requested bean is currently in creation: Is there an unresolvable circular reference?
@SpringBootApplication
@RestController
@EnableDiscoveryClient
@RefreshScope
public class FrontEndApplication {
    @Value("${msg:Hello default}")
    private String message;

    public static void main(String[] args) {
        SpringApplication.run(FrontEndApplication.class, args);
    }

    @Bean
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Autowired
    RestTemplate restTemplate;

}

Solution

  • First, don't put @RefreshScope on the controller. Typically you'd want to do it in a class that stores state. If it's a configuration property it's better to use a @ConfigurationProperty annotation on a POJO and call @EnableConfigurationProperties.

    Also your main class does everything, can you please just separate it into separate classes and try again? It's not a good idea to have your main class also be a controller, repository and a service at the same time.