问题描述
我的JEE应用程序中有2个单例,我想在启动时进行初始化。像这样的东西:
I have 2 singletons in my JEE application that I want to initialize at start up. Something like this:
@Singleton
@Startup
public class ServiceB {
@EJB
private ServiceA a;
@PostConstruct
private void init() {
....
}
}
ServiceB并不需要ServiceA,我只是添加了依赖项以确保ServiceB初始化之前ServiceA已完全初始化(读取:@ PostConstruct-method完成)。 ()-方法开始。
ServiceB doesn't really need ServiceA, I just added the dependency to make sure that ServiceA is fully initialized (read: @PostConstruct-method finished) before ServiceB's init() -Method starts.
但是它不会等待。 ServiceB实际上在ServiceA之前启动。
But it doesn't wait. ServiceB actually starts before ServiceA.
有没有办法确保一个Bean的@ PostConstruct-方法等待另一个Bean的@PostConstruct方法完成?
Is there any way to ensure that one Bean's @PostConstruct- method waits for another Bean's @PostConstruct-method to finish?
我知道我可以删除ServiceA中的@PostConstruct批注并直接从ServiceB中调用它。
I know I could just remove the @PostConstruct Annotation in ServiceA and call it directly from ServiceB
@PostConstruct init() {
a.init();
}
但是我有没有ServiceB的部署。因此,我不能依靠ServiceB来初始化ServiceA。 ServiceA必须自己做。并且ServiceB必须等待ServiceA完成。
but I have deployments where there is no ServiceB. So I can't rely on ServiceB to init ServiceA. ServiceA has to do that itself. And ServiceB must wait for ServiceA to be done with it.
推荐答案
使用批注声明对启动bean的初始化依赖性。
Use the @DependsOn annotation to declare an initialization dependency on startup beans.
示例:
@Singleton
@Startup
public class ServiceA {
@PostConstruct
public void init() { ... }
}
@Singleton
@Startup
@DependsOn("ServiceA")
public class ServiceB {
@EJB
ServiceA a;
@PostConstruct
public void init() { ... } // will be called after a is initialized
}
这篇关于@PostConstruct的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!