How do you prevent Guice from injecting a class not bound in the Module?

我的未来我决定 提交于 2019-12-13 13:13:22

问题


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

Can I prevent Guice from providing an instance of DemoUnbound to the constructor of DemoInstance?

In essence I am looking for a way to run Guice in a totally explicit binding mode where injecting an unbound class is an error.

How do you make it an error to Guice inject a class not bound in the Module?


回答1:


If you use an interface here instead of a concrete class for DemoUnbound, Guice will throw an exception because it cannot find a suitable class to inject:

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



回答2:


Try putting binder().requireExplicitBindings(); in your Module. It won't keep you from injecting concrete classes, but it will require a module to include bind(DemoUnbound.class); to make it more obvious.

Read the Binder docs for more information.



来源:https://stackoverflow.com/questions/12468483/how-do-you-prevent-guice-from-injecting-a-class-not-bound-in-the-module

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!