@RefreshScope 和@Bean 合不来
@RefreshScope can't get along with @Bean
我有一个需要从配置服务器刷新配置的控制器,所以我在上面添加了@RefreshScope。同时这个控制器需要调用后端 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
放在控制器上。通常,您希望在存储状态的 class 中执行此操作。如果是配置 属性 最好在 POJO 上使用 @ConfigurationProperty
注释并调用 @EnableConfigurationProperties
。
你的主 class 也做所有事情,你能不能把它分成单独的 class 然后再试一次?让您的 main class 同时成为控制器、存储库和服务并不是一个好主意。
我有一个需要从配置服务器刷新配置的控制器,所以我在上面添加了@RefreshScope。同时这个控制器需要调用后端 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
放在控制器上。通常,您希望在存储状态的 class 中执行此操作。如果是配置 属性 最好在 POJO 上使用 @ConfigurationProperty
注释并调用 @EnableConfigurationProperties
。
你的主 class 也做所有事情,你能不能把它分成单独的 class 然后再试一次?让您的 main class 同时成为控制器、存储库和服务并不是一个好主意。