如何使用 google guice 绑定 class?

How to bind class by using google guice?

我想使用第三方客户端API。我想创建一个 ServiceClient 实例并使用 postMessage API。我创建了两个类,ServiceClient和ServiceClientAPI 应该怎么绑定呢?非常感谢!


public class ServiceClient {

    @Provides
    @Singleton
    public ServiceClient provideServiceClient() {
        return new ServiceClientBuilder()
                .withEndpoint()
                .withClient(ClientBuilder.newClient())
                .withSystem(SystemBuilder.standard().build())
                .build();
    }



public class ServiceClientAPI {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceClientAPI.class);

    @Inject
    private ServiceClient ServiceClient;

    public Value postMessage(@NonNull Value value) {

        LOGGER.info("Value is " + value);

        try {
            Response response = ServiceClient.postMessage(value);
            return response;
        } catch (Exception ex) {
            String errMsg = String.format("Error hitting the Service");
            LOGGER.error(errMsg, ex);
            throw new Exception(errMsg, ex);
        }
    }

It doesn't work, how should I bind them?

public class ServiceModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(ServiceClient.class).to(ServiceClientAPI.class);
    }
}

看来您在这里混淆了一些概念。

如果你有一个简单的项目。 我建议将客户端构建器移至模块并删除 ServiceClient class。 看起来您的 ServiceClientAPI 是一个包装器,所以不要将 ServiceClient 绑定到 ServiceClientAPI。 @Inject 会为您解决这个问题,只需按原样绑定即可。

public class ServiceModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(ServiceClientAPI.class);
    }

    @Provides
    @Singleton
    public ServiceClient provideServiceClient() {
        return new ServiceClientBuilder()
                .withEndpointFromAppConfig()
                .withClient(ClientBuilder.newClient())
                .withSystem(SystemBuilder.standard().build())
                .build();
    }
  
}

当涉及到更大的项目并且提供有一些逻辑时,您可能希望在他们自己的 class 中使用提供者。 在这种情况下创建一个 ServiceClientProvider

public class ServiceClientProvider implements Provider<ServiceClient> {


    @Override
    public ServiceClient get() {
       return new ServiceClientBuilder()
                .withEndpointFromAppConfig()
                .withClient(ClientBuilder.newClient())
                .withSystem(SystemBuilder.standard().build())
                .build();
    }
}

模块看起来像

public class ServiceModuleWithProvider extends AbstractModule {
    @Override
    protected void configure() {
            bind(ServiceClientAPI.class);
    }

    @Override
    protected void configure() {
        bind(ServiceClient.class)
                .toProvider(ServiceClientProvider.class)
                .in(Singleton.class);
    }
}

https://github.com/google/guice/wiki/ProviderBindings 并且