有没有办法让Guice在Guice.createInjector中快速失败

Yoz*_*tic 7 java ioc-container inversion-of-control guice

我的项目使用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));
        }
    } 
Run Code Online (Sandbox Code Playgroud)

此测试资产已抛出两个异常

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) {
    }
}
Run Code Online (Sandbox Code Playgroud)

caa*_*os0 3

是否有一个参数可以使 Guice 在第一个异常时退出注入器创建?

恐怕不是,不是。

您将必须继续使用类似于您的示例的代码。您可以随时在 Guice 团队的 Google 代码页面上向其建议这一点。