java - @RefreshScope 无法与 @Bean 相处

标签 java spring javabeans spring-cloud

我有一个 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/

相关文章:

Java模仿一等函数

java - 通过spring security(angularjs)获取登录用户的正确方法是什么

javascript - PrimeFaces p :fileUpload multiple files autoComplete only works after first file

JavaBean类规则

java - JSP 中的表单 - 在每个帖子旁边添加日期

java - 诊断 appengine java 后端在已部署的应用程序中挂起

java - 无法使用 mysql 和 hibernate 保存表情符号

java - 有没有办法通过使用 nextLine() 读取空行来退出 while 循环? ( java )

java - 如何在 Spring 中从 JNDI 引用多个 bean?

JavaFX : Consuming REST service and displaying the data in front-end