具有可配置具体类的 Guice 模块

发布于 2025-01-06 03:37:10 字数 479 浏览 0 评论 0原文

如果我有一个定义如下的客户端:-

public interface Client {
    void send(String message);
}

以及如下的实现:-

final class SocketClient {

    private Integer port;

    @Inject
    SocketClient(Integer port) {
        this.port = port;
    }

    @Override
    public void send(String message) {
        System.out.println("Sending message:- "+message+" to port "+port);
    }
}

我将如何使用 Guice 实例化 SocketClient 的多个实例,每个实例连接到不同的端口?

If I have a client defined as follows:-

public interface Client {
    void send(String message);
}

And an implementation as follows:-

final class SocketClient {

    private Integer port;

    @Inject
    SocketClient(Integer port) {
        this.port = port;
    }

    @Override
    public void send(String message) {
        System.out.println("Sending message:- "+message+" to port "+port);
    }
}

How would I use Guice to instantiate multiple instances of the SocketClient, each connecting to different ports?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

π浅易 2025-01-13 03:37:10

我想到的第一个解决方案是创建一个看起来像的 SocketClientFactory 接口

interface SocketClientFactory {
  SocketClient createForPort(int port);
}

,然后使用 辅助注射扩展

The first solution that comes to mind is to create a SocketClientFactory interface that looks like

interface SocketClientFactory {
  SocketClient createForPort(int port);
}

and then get factory instances using the assisted injection extension.

你的往事 2025-01-13 03:37:10

您必须实现诸如单例 PortAllocator 之类的东西,它可以跟踪已分配的端口。然后,您可以将其注入到您的客户端中:

@Inject
SocketClient(PortAllocator portAllocator) {
  this.port = portAllocator.allocatePort();
}

PortAllocator 可能看起来像这样:

@Singleton
class PortAllocator {
  private int nextPort = 1234;

  int allocatorPort() {
    return nextPort++;
  }
}

如果您愿意,您可以使用接口进行解耦。您可能还想考虑线程安全。

您可能会说,您在这里并没有从 Guice 中获得太多好处,但是您获得了内置的单例状态管理,并且静态的缺乏使测试变得容易。

You would have to implement something like a singleton PortAllocator which kept track of the ports it had already allocated. You could then inject that into your client:

@Inject
SocketClient(PortAllocator portAllocator) {
  this.port = portAllocator.allocatePort();
}

PortAllocator might look something like:

@Singleton
class PortAllocator {
  private int nextPort = 1234;

  int allocatorPort() {
    return nextPort++;
  }
}

You could de-couple using an interface if you liked. You might want to think about thread-safety too.

You might argue that you're not getting much out of Guice here, but you are getting the in-built singleton state management and the lack of statics make testing easy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文