Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-依赖项注入-第三方库_Java_Dependency Injection - Fatal编程技术网

Java-依赖项注入-第三方库

Java-依赖项注入-第三方库,java,dependency-injection,Java,Dependency Injection,我正在努力学习依赖注入。通过示例,我编写了以下简单的web服务客户机,它与web服务对话 public class UserWebServiceClient { private Client client; public UserWebServiceClient(String username, String password) { ClientConfig clientConfig = new DefaultApacheHttp

我正在努力学习依赖注入。通过示例,我编写了以下简单的web服务客户机,它与web服务对话

public class UserWebServiceClient
{
    private Client client;

    public UserWebServiceClient(String username, String password)
    {            
        ClientConfig clientConfig = new DefaultApacheHttpClientConfig();
        this.client = ApacheHttpClient.create(clientConfig);
        this.client.addFilter(new HTTPBasicAuthFilter(username, password));
    }

    private WebResource getWebResource()
    {
        WebResource resource = this.client.resource("http://mywebservice/.......");
        return resource;
    }

    public void createUser(String s) throws StorageAPIException
    {
       getWebResource().post(...);
    }
}
这是依赖注入的候选者吗?我应该给客户注射吗


我不想把复杂性推给用户。我想我对何时使用DI感到有点困惑。

是的,如果我遇到这段代码,我会将其更改为:

public class UserWebServiceClient
{
  private Client client;

  public UserWebServiceClient(Client client)
  {
    this.client = client;
  }

  ...
}
注入客户机允许我传递我选择的任何客户机实现,包括模拟实例,以便测试此类

此外,在这种情况下,以这种方式更改类也允许使用ClientConfig的不同实现


简言之,该类变得更加可重用。

是的,如果我遇到此代码,我会将其更改为:

public class UserWebServiceClient
{
  private Client client;

  public UserWebServiceClient(Client client)
  {
    this.client = client;
  }

  ...
}
注入客户机允许我传递我选择的任何客户机实现,包括模拟实例,以便测试此类

此外,在这种情况下,以这种方式更改类也允许使用ClientConfig的不同实现


简而言之,类只是变得更具可重用性了。

最好使用构造函数注入,而不是字段注入。这样做使您能够交换绑定以进行测试。出于同样的原因,分开凭证也很好

然后,您的绑定将通过模块或某种形式的配置提供

有了Guice,它可能看起来像这样

    public class UserWebServiceClient
    {
      private Client client;

      @Inject
      public UserWebServiceClient(Client client)
      {            
        this.client = client;
      }

    ...

    }
你的模块


最好使用构造函数注入,而不是字段注入。这样做使您能够交换绑定以进行测试。出于同样的原因,分开凭证也很好

然后,您的绑定将通过模块或某种形式的配置提供

有了Guice,它可能看起来像这样

    public class UserWebServiceClient
    {
      private Client client;

      @Inject
      public UserWebServiceClient(Client client)
      {            
        this.client = client;
      }

    ...

    }
你的模块


程序员SE站点Di上的好帖子:程序员SE站点Di上的好帖子: