我有一个 Controller 需要从配置服务器刷新配置,因此我在其上添加了@RefreshScope。同时这个 Controller 需要调用后端API,以便我定义restTemplate Bean。但是一旦我启动这个应用程序,就会发生异常。谁能告诉我为什么这两个注释会循环引用?
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;
}
最佳答案
首先,不要将@RefreshScope
放在 Controller 上。通常,您希望在存储状态的类中执行此操作。如果它是配置属性,最好在 POJO 上使用 @ConfigurationProperty
注释并调用 @EnableConfigurationProperties
。
而且你的主类做了所有的事情,你能把它分成单独的类然后再试一次吗?让主类同时成为 Controller 、存储库和服务并不是一个好主意。
关于java - @RefreshScope 无法与 @Bean 相处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60304849/