带参数的自定义 Guice 绑定注释 [英] custom Guice binding annotations with parameters

查看:29
本文介绍了带参数的自定义 Guice 绑定注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功创建了一个 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.

这是一个示例用法:

public class ContainsSingleThreadedExecutorService {


    private final ExecutorService executorService;

    @Inject
    public ContainsSingleThreadedExecutorService(@SingleThreaded ExecutorService executorService) {

        this.executorService = executorService;
    }

}

我现在想为多线程执行器创建一个类似的注解,在注解中指定线程池大小.例如:

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?

推荐答案

你不能.这不是绑定注释的使用方式......该参数仅用于区分与 @MultiThreaded(poolSize = 5) 绑定的 ExecutorService@MultiThreaded(poolSize = 5) 绑定的ExecutorService代码>@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 ExecutorServices 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 绑定注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆