如何进行假装客户端接口的构造函数注入?

How to do constructor injection of the feign client interface?

spring boot 中的 feign client 可以通过构造函数注入注入吗?

@AllArgsConstructor
class ApiPortImpl implements ApiPort {

    private final ApiClient feignClient;

    @Override
    public String getAuthToken() {
        return feignClient.getToken();
    }
}

interface ApiPort {

    String getAuthToken();
}

@FeignClient(name = "api-client", url = "${some_url}", path = "/", configuration = RestConfiguration.class)
interface ApiClient {

    @PostMapping(value = "/identity/token", consumes = "application/x-www-form-urlencoded")
    String getToken();
}

@Configuration
class RestConfiguration {
    
    @Bean
    ApiPort apiPort(){
        return new ApiPortImpl(<how to do constructor injection of the feign client ??>);
    }
}

我不想使用@Component 注释。 在上面提到的代码块中,如何实例化 ApiPortImpl bean?

您可以将 ApiClient 作为参数注入到使用 @Bean 注释的方法中:

@Configuration
class RestConfiguration {
    
    @Bean
    ApiPort apiPort(@Autowired ApiClient apiClient){
        return new ApiPortImpl(apiClient);
    }
}

即使没有@Autowired 注释也应该可以工作。

文档参考:Declaring a Bean