问题描述
我已经成功创建了一个Guice绑定注释,将单线程java.util.concurrent.ExecutorService实例注入到构造函数中。
I have successfully created a Guice binding annotation to inject single threaded java.util.concurrent.ExecutorService instances into a constructor.
这里是一个示例用法: p>
here is an example usage:
public class ContainsSingleThreadedExecutorService {
private final ExecutorService executorService;
@Inject
public ContainsSingleThreadedExecutorService(@SingleThreaded ExecutorService executorService) {
this.executorService = executorService;
}
}
我现在想创建一个类似的多线程执行器的注释,在注释中指定ThreadPool大小。例如:
I now want to create a similar annotation for multi-threaded executors, specifying the ThreadPool size in the annotation. For example:
public class ContainsMultiThreadedExecutorService {
private final ExecutorService executorService;
@Inject
public ContainsMultiThreadedExecutorService(@MultiThreaded(poolSize = 5) ExecutorService executorService) {
this.executorService = executorService;
}
}
有没有人知道我可以从Guice Provider访问poolSize参数的值?
Does anyone out there know how I can access the value of the "poolSize" parameter from a Guice Provider?
推荐答案
你不能。这不是如何使用绑定注释?该参数仅用于区分 ExecutorService
与 @MultiThreaded(poolSize = 5)绑定,
与 @MultiThreaded(poolSize = 2)
绑定。这不是帮助配置 Provider
的元数据。
You can't. That's not how binding annotations are intended to be used... the parameter would only serve to differentiate an ExecutorService
bound with @MultiThreaded(poolSize = 5)
from one bound with @MultiThreaded(poolSize = 2)
. It's not metadata to help configure a Provider
.
如果您使用 @ MultiThreaded(poolSize = 5)
,您需要使用注释 @MultiThreaded(poolSize = 5)
绑定某些东西。如果您要更改所有这些地方使用的池大小,则需要将 poolSize = 5
更改为 poolSize = 4
在你绑定它的地方和你注入的所有地方。这对我来说没有什么意义。
If you inject something annotated with @MultiThreaded(poolSize = 5)
, you need to have bound something with the annotation @MultiThreaded(poolSize = 5)
. If you then want to change the pool size you're using in all those places, you need to change poolSize = 5
to poolSize = 4
in both the place(s) where you bind it and in all the places you inject it. This doesn't make much sense to me.
而不是通过他们拥有的线程来绑定 ExecutorService
他们的线程池,你应该根据你想要使用它们来绑定它们。然后,您可以在一个位置调整每个用户的线程数。
Instead of binding ExecutorService
s by how many threads they have in their thread pool, you should bind them according to what you want to use them for. Then you can adjust the numbers of threads each one uses in one place.
这篇关于自定义Guice绑定注释与参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!