我正在尝试学习依赖注入(inject)。例如,我编写了以下简单的 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(...);
}
}
这是依赖注入(inject)的候选者吗?我应该注入(inject)客户端吗?
我不想把它的复杂性推给用户。我想我对何时使用 DI 有点困惑。
最佳答案
是的,如果我遇到这段代码,我会将其更改为:
public class UserWebServiceClient
{
private Client client;
public UserWebServiceClient(Client client)
{
this.client = client;
}
...
}
注入(inject) Client
允许我传递我选择的任何 Client
实现,包括模拟实例以测试此类。
此外,在这种情况下,以这种方式更改类还允许使用不同的 ClientConfig
实现。
简而言之,该类变得更加可重用。
关于Java - 依赖注入(inject) - 第三方库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22101191/