WebClient do it myself



我在这里遵循这个教训:https://www.baeldung.com/spring-webclient-oauth2我试图建立一个服务类,以访问来自其他API的资源与给定的clientId &clientSecret(在Postman &昂首阔步)。

Next, we'll set the webClient instance that we autowired in our scheduled task:
@Bean
WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations) {
ServerOAuth2AuthorizedClientExchangeFilterFunction oauth =
new ServerOAuth2AuthorizedClientExchangeFilterFunction(
clientRegistrations,
new UnAuthenticatedServerOAuth2AuthorizedClientRepository());
oauth.setDefaultClientRegistrationId("otherClientId");
return WebClient.builder()
.filter(oauth)
.build();
}

我有点困惑,不知道我应该把这些代码放在哪里?我应该把它放在类WebClient.java在我的项目的配置包?

我试图把这些代码放在我的服务类,我得到这个错误消息:

nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: 
Error creating bean with name 'xxxService': Requested bean is currently in creation: 
Is there an unresolvable circular reference? 
我的xxxService类中的代码是这样的:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
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;
@Slf4j
@Service
public class xxxService{
@Autowired
private WebClient wclient;

public void getAuthThenGetResource(){
... 
log.info("got token");
...
log.info("got response");
}
}
非常感谢你的帮助。

虽然您可以在Service类中声明Spring bean,但它应该在单独的Configuration类中声明。而且,您得到这个错误是因为您在声明bean的同一个服务中自动装配了该bean。

有几种方法可以解决这个问题。一种是使用定义Configuration类的约定,如下所示。理想情况下,这个类也应该放在项目结构中的另一个包中。

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

另一个,我不打算展示,是通过使用ReactiveClientRegistrationRepository调用bean声明函数(即webClient(clientRegistrations)),您可以使用Autowire而不是WebClient。这不是正确的做法。我只是想提一下处理依赖注入错误的其他方法。

相关内容

最新更新