如何通过Guice Multibinding结合Named Binding分集合绑定Processor实例
用Guice Multibinding实现多Processor集合分组
当然可以用Guice Multibinding实现这个需求,核心是利用注解区分不同的集合,和常规bind()的annotatedWith()逻辑一致,只是Multibinding的写法稍有不同,不需要额外编写自定义集合方法。
具体实现步骤
- 定义自定义注解:为每个Processor集合创建专属注解,用来标记不同分组:
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER}) public @interface FastProcessors {} @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER}) public @interface SlowProcessors {}
- 绑定带注解的Multibinder:在Module中,针对不同注解创建对应的Multibinder,再向各自Binder中添加对应配置的Processor实例:
public class ProcessorModule extends AbstractModule { @Override protected void configure() { // 绑定FastProcessors分组(高配置实例) Multibinder<Processor> fastBinder = Multibinder.newSetBinder(binder(), Processor.class, FastProcessors.class); fastBinder.addBinding().toInstance(new ProcessorImpl("high-speed-config")); fastBinder.addBinding().to(HighPerformanceProcessor.class); // 绑定SlowProcessors分组(低配置实例) Multibinder<Processor> slowBinder = Multibinder.newSetBinder(binder(), Processor.class, SlowProcessors.class); slowBinder.addBinding().toInstance(new ProcessorImpl("low-cost-config")); slowBinder.addBinding().to(LowPowerProcessor.class); } }
- 注入对应分组的集合:在需要使用的地方,通过注解指定要注入的目标集合:
public class ProcessorManager { private final Set<Processor> fastProcessors; private final Set<Processor> slowProcessors; @Inject public ProcessorManager( @FastProcessors Set<Processor> fastProcessors, @SlowProcessors Set<Processor> slowProcessors) { this.fastProcessors = fastProcessors; this.slowProcessors = slowProcessors; } // 业务逻辑中使用不同分组的Processor }
简化方案:用命名绑定区分
如果不想自定义注解,也可以直接用Names.named()标记不同集合:
// 绑定阶段 Multibinder<Processor> fastBinder = Multibinder.newSetBinder(binder(), Processor.class, Names.named("fast-processors")); Multibinder<Processor> slowBinder = Multibinder.newSetBinder(binder(), Processor.class, Names.named("slow-processors")); // 注入阶段 @Inject public ProcessorManager( @Named("fast-processors") Set<Processor> fastProcessors, @Named("slow-processors") Set<Processor> slowProcessors) { // ... }
内容的提问来源于stack exchange,提问作者Belphegor21
相关产品推荐
相关产品推荐

