具有可配置具体类的 Guice 模块
如果我有一个定义如下的客户端:-
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想到的第一个解决方案是创建一个看起来像的
SocketClientFactory
接口,然后使用 辅助注射扩展。
The first solution that comes to mind is to create a
SocketClientFactory
interface that looks likeand then get factory instances using the assisted injection extension.
您必须实现诸如单例 PortAllocator 之类的东西,它可以跟踪已分配的端口。然后,您可以将其注入到您的客户端中:
PortAllocator 可能看起来像这样:
如果您愿意,您可以使用接口进行解耦。您可能还想考虑线程安全。
您可能会说,您在这里并没有从 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:
PortAllocator might look something like:
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.