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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With