Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

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?

like image 462
Alain O'Dea Avatar asked Sep 17 '12 23:09

Alain O'Dea


1 Answers

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.

like image 60
Jeff Bowman Avatar answered Nov 13 '22 04:11

Jeff Bowman