Spring Boot Sping Boot 2.7.9 -应用程序上下文中某些bean的依赖关系形成了一个循环restTemplate

xsuvu9jc  于 2023-03-02  发布在  Spring
关注(0)|答案(2)|浏览(246)

我使用的是Sping Boot 应用程序版本2.7.9。在从RestTemplateBuilder创建restTemplate时,我遇到以下异常:

The dependencies of some of the beans in the application context form a cycle:

???->???
|  srGroupController (field org.springframework.web.client.RestTemplate com.example.demo.SrGroupController.restTemplate)
???<-???


@RestController
@RequestMapping("/api/srgrp/")
public class SrGroupController {    
        
    @Autowired
    @Qualifier("jiraRT")
    RestTemplate restTemplate;  
    
    @Bean(name = "jiraRT")
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.basicAuthentication("myuser", "paswword").build();
    }
    
    
    @RequestMapping (value = "ping", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
    public String ping() {  
        
        return "ping works!";       
    }   
}
bpzcxfmw

bpzcxfmw1#

需要向restTemplate方法添加静态修饰符

7z5jn7bk

7z5jn7bk2#

将其添加到www.example.com文件中。application.properties file.

spring.main.allow-circular-references:true

如果您使用的是application. yml,则

spring:
   main:
    allow-circular-references: true

您也可以使用@lazy
@lazy将打破循环依赖,要求Spring惰性地初始化其中一个bean。它将创建一个代理来将其注入到另一个bean中。被注入的bean将仅在第一次需要时被完全创建。
您可以选择其中的任何一个,我希望尽可能减少循环依赖,因为它会影响应用程序启动时的性能。

相关问题