带有可选Nullable注入的Guice @Provides函数不起作用

时间:2015-05-20 03:24:56

标签: java inversion-of-control guice

代码优先:

@Slf4j
public class HelperModule extends AbstractModule
{
    @Override
    protected void configure()
    {

    }

    @Provides
    @Named("plugin")
    @Singleton
    public Reflections getReflections(@Nullable @Named("plugin-scope") String pluginScope)
    {
        if (pluginScope == null)
        {
            pluginScope = "me.wener";
        }
        log.info("Create plugin scanner for '{}'", pluginScope);
        return new Reflections(new ConfigurationBuilder()
                .setUrls(ClasspathHelper.forPackage(pluginScope))
                .addScanners(
                        new SubTypesScanner(),
                        new TypeAnnotationsScanner())
//                .filterInputsBy(new FilterBuilder().include(".*\\.java").exclude(".*"))
        );
    }
}

我期望的是pluginScope可以为空且可选,我按照Use @Nullable指令操作,但这不起作用,我仍然有

No implementation for java.lang.String annotated with @com.google.inject.name.Named(value=plugin-scope) was bound

出了什么问题?

修改 顺便说一句,@Nullablejavax.annotation.Nullable

1 个答案:

答案 0 :(得分:3)

@Nullable注释意味着您可以绑定到返回null的提供者,而不是绑定可能不存在。你的@Nullable注释是允许以下工作的:

bind(String.class).annotatedWith(Names.named("plugin-scope"))
    .toProvider(Providers.<String>of(null));

根据internal Guice error message,您明确必须绑定到null的提供者,而不是toInstance(null)