Java 如何防止Guice注入模块中未绑定的类?

Java 如何防止Guice注入模块中未绑定的类?,java,guice,Java,Guice,我可以阻止Guice向DemoInstance的构造函数提供DemoUnbound的实例吗 本质上,我正在寻找一种在完全显式绑定模式下运行Guice的方法,在这种模式下,注入未绑定的类是一种错误 如何使Guice在模块中注入未绑定的类成为错误?如果在此处使用接口而不是具体的类来解除绑定,Guice将抛出异常,因为它找不到合适的类来注入: import com.google.inject.AbstractModule; import com.google.inject.Guice; import

我可以阻止Guice向DemoInstance的构造函数提供DemoUnbound的实例吗

本质上,我正在寻找一种在完全显式绑定模式下运行Guice的方法,在这种模式下,注入未绑定的类是一种错误


如何使Guice在模块中注入未绑定的类成为错误?

如果在此处使用接口而不是具体的类来解除绑定,Guice将抛出异常,因为它找不到合适的类来注入:

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;

public class GuiceDemo
{
    public static void main(String[] args)
    {
        new GuiceDemo().run();
    }

    public void run()
    {
        Injector injector = Guice.createInjector(new EmptyModule());
        DemoInstance demoInstance = injector.getInstance(DemoInstance.class);
        assert(demoInstance.demoUnbound == null);
    }

    public static class EmptyModule extends AbstractModule
    {
        @Override
        protected void configure()
        {
        }
    }

    public static class DemoInstance
    {
        public final DemoUnbound demoUnbound;

        @Inject
        public DemoInstance(DemoUnbound demoUnbound)
        {
            this.demoUnbound = demoUnbound;
        }
    }

    public static class DemoUnbound
    {
    }
}
尝试放置
binder().requireExplicitBindings()在您的模块中。它不会阻止您注入具体的类,但它需要一个模块来包含
bind(DemoUnbound.class)以使其更加明显


有关详细信息。

有效的解决方案。我应该澄清我的意图。问题是我想阻止程序员注入已经存在的公共类。超越编译器的界限,我仍然看不到解决这个问题的方法。我想解决方案是代码审查:我想我需要一些澄清。你所说的“我想阻止程序员注入已经存在的公共类”是什么意思?我想让上面提供的代码不起作用。我希望它能让我被迫使用“bind(DemoInstance.class,DemoInstance.class)”来使它工作。Guice支持这个吗?基本上,这已被确定为一个致命的缺陷,并可能导致从我们的代码中大规模删除Guice。我们想要明确地控制可以注入的类型。老实说,这听起来像是一个奇怪的请求。为什么这是一个致命的缺陷?是什么阻止开发人员只执行以下操作:DemoInstance instance=new DemoInstance(new DemoUnbound())?我同意你的看法。我将说明,代码审查可以很容易地发现不合适的构造函数参数。不幸的是,DI框架是一个很难推销的东西,人们似乎可以创造性地反对它们:)@johncarl谢谢你的语法修复。我不喜欢我的原始代码,因为它正在从构造函数中进行演示,这很难看:)我应该在发布之前检查代码。这听起来似乎符合要求。。。我不知道这个配置。
public class GuiceDemo
{
    public static void main(String[] args)
    {
        new GuiceDemo().run();
    }

    public void run()
    {
        Injector injector = Guice.createInjector(new EmptyModule());
        DemoInstance demoInstance = injector.getInstance(DemoInstance.class);
        assert(demoInstance.demoUnbound == null);
    }

    public static class EmptyModule extends AbstractModule
    {
        @Override
        protected void configure()
        {
        }
    }

    public static class DemoInstance
    {
        public final DemoUnbound demoUnbound;

        @Inject
        public DemoInstance(DemoUnbound demoUnbound)
        {
            this.demoUnbound = demoUnbound;
        }
    }

    public interface DemoUnbound
    {
    }
}