问题
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