Search code examples
springdependency-injectionguice

How to specify object instantiation order in guice?


I'm creating two objects in two Guice modules, Object1 and Object2. Both these objects use Object3. How can I control the order in which Guice instantiates Object1 and Object2 (Object 1 before 2) as the state of Object3 set by Object1 is required for Object2 ? In spring this is similar to having a @DependsOn. But I couldn't find anything similar in Guice.

GuiceModule1
    Object1(Object3)
GuiceModule2
    Object2(Object3)

A way that I think could solve this is by passing Object2 as a parameter when constructing Object1, but that doesn't sound the right way as I have to do this just to define dependency creation order.


Solution

  • You can't enforce injection order in Guice via some annotation or built-in mechanism.

    But you can trick Guice to enforce injection order by means of requiring class Object2 to hold a reference to Object1 without doing anything with the reference. It's definitely not clean but gets the job done easily.

    Hint for dependency injection best practices

    If it's possible you should restructure your class design in a way that injection order doesn't matter. The dependency order should be the only driver of injection order and this is where Guice or other DI frameworks excel.

    Perhaps that's the reason why Guice doesn't provide such a built-in mechanism to enforce injection order as it comes with some other cost such as maintenance of the annotation and even some contradiction if your references change drastically so that the annotation would be the opposite of what your depdency graph says. I think you see where I'm heading to.

    Without more information about your app it's difficult to give advice about how to do it "better".

    Anyway I hope it helped!