2017-09-24 550 views
1

我在我的JEE應用程序中有2個單例,我想在啓動時進行初始化。事情是這樣的:@PostConstruct的執行順序

@Singleton 
@Startup 
public class ServiceB { 

    @EJB 
    private ServiceA a; 

    @PostConstruct 
    private void init() { 
     .... 
    } 
} 

ServiceB並不真正需要ServiceA,我只是說相關性,以確保ServiceA完全初始化(讀:@ PostConstruct法完成)ServiceB的init()之前 - 方法開始。

但它不等。 ServiceB實際上是在ServiceA之前啓動的。

是否有任何方法可以確保一個Bean的@ PostConstruct-方法等待另一個Bean的@ PostConstruct方法完成?

我知道我可以只取出@PostConstruct註釋中ServiceA,直接從ServiceB

@PostConstruct init() { 
     a.init(); 
    } 

調用它,但我有部署中沒有ServiceB。所以我不能依靠ServiceB來啓動ServiceA。 ServiceA必須自己做。 ServiceB必須等待ServiceA完成。

回答

3

使用@DependsOn註釋來聲明啓動Bean的初始化依賴關係。

實施例:

@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 
}