2012-09-07 285 views
4

期间快速失败我的项目使用Guice作为IOC容器负责提供依赖性(服务类)到对象的大图(主要是单身人士)。有时,如果依赖项在构建过程中失败,并且这种依赖关系是很多对象所必需的,那么失败将会一遍又一遍地向Guice ProvisionException添加例外。有没有办法让Guice在Guice.createInjector

我可以理解这种行为的理性,因为它给出了所有发生的错误列表,以保存修复问题片餐。但是,我想禁用此功能并且“快速失败”,因为此情况下的重复失败是资源密集型的。此外,'ProvisionException'包含相同异常的列表。我确实明白这种行为在实现(如资源密集型对象创建)中是不良实践的症状(气味),但由于依赖关系是任何人都可以使用依赖注入提供实现和插件的抽象,所以几乎没有什么防御措施反对。

我想知道的是: -

有使吉斯在第一个异常退出喷油器创建参数?

任何帮助将不胜感激。

编辑:

@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

你可以添加你的具体例子吗?我只是试图分析它,总是得到发生的第一个配置错误,而不是所有可能的错误列表... –

+0

我将在稍后添加一个简单示例。但是,请注意'ProvisionException'是引导过程中引发的异常集合的一个包装异常。所以你只会得到一个'ProvisionException'它会一遍又一遍地包含相同的真正的异常。 – Yoztastic

+0

我知道,编辑'绑定(IWasDesignedWithHonestIntent.class).to(NastyThrowingExample.class).asEagerSingleton();'对于上面的示例它只会引发一个异常。但是我的问题是,Guice是否有一个选项可以快速避免在每个可能失败的绑定上放置'.asEagerSingleton()',或者如果我不想单身对象。 – Yoztastic

回答

2

有使吉斯在第一个异常退出喷油器创建参数?

恐怕不这样做,事实并非如此。

您将不得不继续使用类似于您的示例的代码。 您可以随时在Google代码页上为Guice团队提出此建议。