You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring WebClient OAuth2配置位置疑问及循环依赖问题求助

问题根源

你把@Bean方法写在@Service类里导致了循环依赖:Spring创建xxxService时,会先处理类内的@Bean去生成WebClient实例,但xxxService本身又依赖WebClient,形成了无法解析的循环创建链,所以抛出BeanCurrentlyInCreationException。

解决方案

1. 把WebClient配置移到专门的配置类

在项目的config包下新建WebClientConfig.java,用@Configuration标记,将WebClient的Bean配置代码放在这里:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction;
import org.springframework.security.oauth2.client.web.server.UnAuthenticatedServerOAuth2AuthorizedClientRepository;
import org.springframework.web.reactive.function.client.WebClient;

@Configuration
public class WebClientConfig {

    @Bean
    WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations) {
        ServerOAuth2AuthorizedClientExchangeFilterFunction oauth =
                new ServerOAuth2AuthorizedClientExchangeFilterFunction(
                        clientRegistrations,
                        new UnAuthenticatedServerOAuth2AuthorizedClientRepository());
        oauth.setDefaultClientRegistrationId("otherClientId");
        return WebClient.builder()
                .filter(oauth)
                .build();
    }
}

2. 清理你的服务类代码

删掉xxxService里所有和@Bean相关的代码及对应导入,只保留业务逻辑和WebClient注入:

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

@Slf4j
@Service
public class xxxService{
    @Autowired
    private WebClient wclient;
  
    public void getAuthThenGetResource(){
        // 你的业务逻辑代码
        log.info("got token");
        // ...
        log.info("got response");
    }
}

3. 确保OAuth2客户端配置正确

在application.yml(或application.properties)里补充第三方API的OAuth2客户端信息:

spring:
  security:
    oauth2:
      client:
        registration:
          otherClientId:
            client-id: 你的clientId
            client-secret: 你的clientSecret
            authorization-grant-type: client_credentials
            scope: 第三方API要求的权限范围
        provider:
          otherClientId:
            token-uri: 第三方平台的Token获取地址

内容的提问来源于stack exchange,提问作者surianto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 04:32:43