EJB Singleton 服务在部署时失败

EJB Singleton service fails at deploy

我是 JBoss 和注释的新手。我有以下代码示例。不相关的细节都删掉了。

@Singleton
@Startup
public class SomeBean {

    @Resource
    TimerService timerService;

    @Inject
    AnotherSingleton anotherOne;

    Timer timer;

    @PostConstruct
    private void ejbCreate() {
        timer = timerService.createIntervalTimer(0, interval, tc);
    }

    @Timeout
    public void run() throws Exception {
    }
}

@Singleton
public class AnotherSingleton {

    @Inject
    Repository rep;
}

当 war 在 JBoss 上部署时,它会因存储库生产者的异常而失败(另一个 Jboss 中的服务不可用)。

Caused by: java.lang.IllegalStateException: WFLYEE0042: Failed to construct component instance

所以流程结束于

WFLYCTL0186:   Services which failed to start:      service jboss.deployment.unit."someservices-view.war".component.SomeBean.START

我有什么选择? 我可以告诉 JBoss 不要在启动时 @Inject bean 但当计时器执行代码时吗? 我能以某种方式捕获异常吗? @Schedule 是不可能的,因为我需要配置定时器。

注入由 CDI specification which provides a feature to "wrap" injections as it were, like so 处理。

@Inject
Instance<AnotherSingleton> anotherOneInstance;

这基本上围绕 AnotherSingleton 创建了一个代理,您可以在需要时延迟获取对它的实际引用。

AnotherSingleton anotherOne = anotherOneInstance.get();

这应该可以让部署成功并且您的计时器可以初始化,但是当然如果此时您尝试使用 anotherOne 并且存储库不可用,代码仍然会因异常而中断。

或者,您始终可以 manual lookup through the BeanManager 不必依赖任何形式的依赖项注入,但这应该始终是最后的手段,因为它只会导致繁琐的代码。