Search code examples
javaguice

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


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?


Solution

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