如何使用googleguice绑定类?

chy5wohz  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(371)

我想使用第三方客户端api。我想创建一个serviceclient示例并使用postmessageapi。我创建了两个类,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);
    }
}
tag5nh1u

tag5nh1u1#

看起来你在混合一些概念。
如果你有一个简单的项目。我建议将客户机生成器移到模块中,并删除serviceclient类。看起来serviceclientapi是一个 Package 器,所以不要将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();
    }

}

当涉及到更大的项目和提供程序时,您可能希望在它们自己的类中使用提供程序。在本例中,创建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 guice@提供方法和提供程序类

相关问题