Search code examples
javacdijava-ee-7

Is there a way of defining the order by which cdi is going to destroy instances?


I'm developing an application where I have some services being injected. Once the application shuts down, I would like to define an order by which my destroy() functions are called.

For instance, "Service A needs to shut down before service B".

Is there a way of doing such a thing?


Solution

  • Suppose you have two objects, A and B, with no relationship to one another, in, say, @Singleton scope (just an arbitrary scope). To my knowledge there is no defined order around when their producing Beans' destroy() methods will be called: A could be destroyed first or B could be destroyed first.

    Suppose instead now you have these three objects:

    1. A in @Singleton scope (again, an arbitrary scope)
    2. B in @Dependent scope, injected into A
    3. C in @Dependent scope, injected into B

    In this case, again assuming we're talking about custom beans and not managed beans, C will be destroyed first, then B, then A.

    To my knowledge that is the only ordering guarantee offered by the specification.