你如何阻止Guice注入一个没有绑定在模块中的类?

时间:2012-09-17 23:30:47

标签: java 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
    {
    }
}

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

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

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

2 个答案:

答案 0 :(得分:9)

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

Read the Binder docs了解更多信息。

答案 1 :(得分:5)

如果你在这里使用接口而不是DemoUnbound的具体类,Guice会抛出一个异常,因为它找不到合适的类来注入:

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
    {
    }
}