我的项目使用Guice作为IOC容器,负责为大对象(主要是单例)提供依赖关系(服务类)。有时,如果在构造期间依赖项失败并且许多对象需要此依赖项,则会一次又一次地将失败添加到Guice ProvisionException
中。
我可以理解这种行为的理性,因为它列出了为节省修复问题而发生的所有错误。但是,我想禁用此功能并“快速失败”,因为在这种情况下重复失败是资源密集型的。此外,'ProvisionException'包含相同异常的列表。
我确实感谢这种行为在实现(即资源密集型对象创建)中有不良做法的症状(气味),但由于依赖性是任何人都可以使用依赖注入提供实现和插件的抽象,因此几乎没有防范它。
我想知道的是: -
是否有一个参数可以让Guice在第一个例外时退出Injector创建?
非常感谢任何帮助。
编辑:
@Test
public void guiceExample()
{
Injector injector = Guice.createInjector(new TestModule());
try{
IAmANeedyObject instance = injector.getInstance(IAmANeedyObject.class);
}
catch (ProvisionException e)
{
assertThat(e.getErrorMessages().size(),Is.is(2));
}
}
此测试资产已抛出两个异常
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
public class TestModule extends AbstractModule {
@Override
protected void configure() {
bind(IWasDesignedWithHonestIntent.class).to(NastyThrowingExample.class);
bind(IMindMyOwnBusiness.class).to(SomeLucklessObject.class);
bind(IAlsoMindMyOwnBusiness.class).to(SomeEquallyLucklessObject.class);
bind(IAmANeedyObject.class).to(LowSelfEsteem.class);
}
}
interface IWasDesignedWithHonestIntent {}
interface IMindMyOwnBusiness {}
interface IAlsoMindMyOwnBusiness {}
interface IAmANeedyObject {}
@Singleton
class NastyThrowingExample implements IWasDesignedWithHonestIntent {
@Inject
public NastyThrowingExample() throws LongSlowAgonisingDeathException {
throw new LongSlowAgonisingDeathException("I am dying");
}
}
class LongSlowAgonisingDeathException extends Exception {
@Inject
public LongSlowAgonisingDeathException(String message) {
super(message);
}
}
class SomeLucklessObject implements IMindMyOwnBusiness {
@Inject
public SomeLucklessObject(IWasDesignedWithHonestIntent designedWithHonestIntent) {
}
}
class SomeEquallyLucklessObject implements IAlsoMindMyOwnBusiness {
@Inject
public SomeEquallyLucklessObject(IWasDesignedWithHonestIntent designedWithHonestIntent) {
}
}
class LowSelfEsteem implements IAmANeedyObject {
@Inject
public LowSelfEsteem(IMindMyOwnBusiness iMindMyOwnBusiness, IAlsoMindMyOwnBusiness alsoMindMyOwnBusiness) {
}
}
答案 0 :(得分:2)
是否有一个参数可以让Guice在第一个例外时退出Injector创建?
我害怕不这样做,但事实并非如此。
您必须继续使用类似示例的代码。 您可以随时在Google代码页上为Guice团队提供此建议。