Execution Order of @PostConstruct

我怕爱的太早我们不能终老 提交于 2019-12-10 17:48:44

问题


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 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.

But it doesn't wait. ServiceB actually starts before ServiceA.

Is there any way to ensure that one Bean's @PostConstruct- method waits for another Bean's @PostConstruct-method to finish?

I know I could just remove the @PostConstruct Annotation in ServiceA and call it directly from ServiceB

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

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.


回答1:


Use the @DependsOn annotation to declare an initialization dependency on startup beans.

Example:

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



回答2:


A question on the answer given by @DmiN (I am new user so not able to post a comment directly)

With your suggestion (as shown in code below) -- I agree that Service B will start after Service A is initialized (just initialized, not that postconstruct is complete). But I doubt if it can be guaranteed that ServiceB's init method will never run unless the Service A's PostConstruct method has finished execution? Correct?

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


来源:https://stackoverflow.com/questions/46393645/execution-order-of-postconstruct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!