Is it possible to guarantee the order in which @PostConstruct methods are invoked? Is it possible to guarantee the order in which @PostConstruct methods are invoked? spring spring

Is it possible to guarantee the order in which @PostConstruct methods are invoked?


You might instead have the Set of Animals @Injected into the Zoo.

@Componentpublic class Zoo {    @Inject    private Set<Animal> animals = new HashSet<Animal>();    // ...}

Then Zoo's @PostConstruct should only be called once all the Animals are injected. The only gotcha is that there must be at least one Animal in the system, but it doesn't sound like that should be an issue.


I don't think there is a way to ensure @PostConstruct order without introducing dependencies.

I think you're looking for trouble trying to mix injection or self registration. To some extent, @PostConstruct call order should not matter - if it does, it might not be the right tool for the job.

A couple ideas for your example

  • try to have an @Autowired on Zoo#animals: no need for self-registration by animals, also the zoo is aware of the animals but not the reverse, which feels cleaner
  • keep the register, but let external actors do the registration (someone is putting the animals in the zoo, right? - they're not showing up at the entrance all by themselves)
  • if you need to insert new animals at any time, but don't want manual insertion, do a more dynamic accessor on zoo: don't store the list of animals, but use the spring context to get all existing instances of the interface.

I don't think there is a 'right' answer, it all depends on your use case.


Reframe your problem so that it doesn't rely on invocation order.