我的项目使用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) {
}
}