Java 提供者可以在不同的实例之间进行选择吗

Java 提供者可以在不同的实例之间进行选择吗,java,dependency-injection,guice,Java,Dependency Injection,Guice,我有一个绑定一个类的多个实例的设置。类之间的区别是一个输入参数。始终注入这两个实例 绑定看起来像这样 CmsExportAwsWriterSingle cmsExportAwsWriterSingleTranslation = new CmsExportAwsWriterSingle("testing-v1", getCredentials(id, secret)); bind(CmsExportWriter.class) .annotatedWith(Names.named("config:e

我有一个绑定一个类的多个实例的设置。类之间的区别是一个输入参数。始终注入这两个实例

绑定看起来像这样

CmsExportAwsWriterSingle cmsExportAwsWriterSingleTranslation = new CmsExportAwsWriterSingle("testing-v1", getCredentials(id, secret));
bind(CmsExportWriter.class)
.annotatedWith(Names.named("config:export.writer.translation"))
.toInstance(cmsExportAwsWriterSingleTranslation);

CmsExportAwsWriterSingle cmsExportAwsWriterSingleReview = new CmsExportAwsWriterSingle("prod-v1", getCredentials(id, secret));
bind(CmsExportWriter.class)
.annotatedWith(Names.named("config:export.writer.review"))
.toInstance(cmsExportAwsWriterSingleReview);
现在我有两个服务,它们使用javax.injectprovider给我一个writer实例

@Inject
public ServiceOne(Provider<CmsExportWriter> writer) {
   CmsExportWriter writer = writer.get();
}

@Inject
public ServiceTwo(Provider<CmsExportWriter> writer) {
   CmsExportWriter writer = writer.get();
}
仅仅使用@Named不会像提供商那样给我额外的好处。我需要每次都有新的作家


看起来应该改为注入提供程序。

提供程序用于在每次调用其get方法时创建一个新实例。这适用于在创建封闭对象时不能/不应该注入依赖实例,或者需要多个实例等情况。这与多绑定的注入无关

使用多个绑定注入实例的正确方法是通过绑定注释。有两种类型的绑定注释:内置@Named注释或自定义注释,它们应该根据标准模板实现


您可以找到一些示例

提供程序用于在每次调用其get方法时创建新实例。这适用于在创建封闭对象时不能/不应该注入依赖实例,或者需要多个实例等情况。这与多绑定的注入无关

使用多个绑定注入实例的正确方法是通过绑定注释。有两种类型的绑定注释:内置@Named注释或自定义注释,它们应该根据标准模板实现

你可以找到一些例子

public ServiceTwo(@Named("config:export.writer.review") CmsExportWriter writer)