【问题标题】:Guice Module With Configurable Concrete Class具有可配置具体类的 Guice 模块
【发布时间】:2012-02-15 20:39:23
【问题描述】:

如果我的客户定义如下:-

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 的多个实例,每个实例连接到不同的端口?

【问题讨论】:

    标签: java guice


    【解决方案1】:

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

    interface SocketClientFactory {
      SocketClient createForPort(int port);
    }
    

    然后使用assisted injection extension 获取工厂实例。

    【讨论】:

    • 辅助注射看起来像我所追求的。
    【解决方案2】:

    您必须实现类似单例的 PortAllocator 来跟踪它已经分配的端口。然后您可以将其注入您的客户端:

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

    PortAllocator 可能类似于:

    @Singleton
    class PortAllocator {
      private int nextPort = 1234;
    
      int allocatorPort() {
        return nextPort++;
      }
    }
    

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

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

    【讨论】:

    • 好答案,但我也知道我想连接的端口。
    • 是的,我对您的问题的解释略有不同。 AssistedInject 或工厂模式看起来确实是正确的方法。
    猜你喜欢
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多