如何防止Guice注入模块中未绑定的类? [英] How do you prevent Guice from injecting a class not bound in the Module?
本文介绍了如何防止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
{
}
}
我可以阻止Guice向DemoInstance的构造函数提供DemoUnbound的实例吗?
Can I prevent Guice from providing an instance of DemoUnbound to the constructor of DemoInstance?
本质上,我正在寻找一种在完全显式绑定模式下运行Guice的方法,其中注入未绑定的类是错误的.
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.
Guice注入未在模块中绑定的类如何使您出错?
How do you make it an error to Guice inject a class not bound in the Module?
推荐答案
如果您在此处使用接口而不是DemoUnbound的具体类,那么Guice将抛出异常,因为它找不到合适的注入类:
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
{
}
}
这篇关于如何防止Guice注入模块中未绑定的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文