Skip to content
Advertisement

If a spring singleton bean has a dependency to another bean, will they be destroyed in the reverse order they were created in?

This is a question about the default behavior of Spring. Say I have a singleton bean called BeanA, which has a constructor dependency to a singleton bean called BeanB. BeanB will have to be created before BeanA in order to satisfy that dependency. If both beans implement the DisposableBean interface I would expect the destroy method to be called in the reverse order that the beans were created in, but I can’t see it mentioned in the documentation. The best I’ve found is the documentation for the DependsOn annotation (https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/DependsOn.html) but it doesn’t mention what the behavior is when DependsOn isn’t used.

Edit: As I mentioned in a comment below: I’ve tried this out and in my test it works as expected. BeanA is destroyed before BeanB. I would like some documentation or similar to know that this is always the case though.

Advertisement

Answer

After testing and looking through the Spring source code (for example the DefaultSingletonBeanRegistry mentioned by M. Deinum in a comment) I have found that two singleton beans where one is dependendent on the other will indeed be destroyed in the reverse order they are created in. When thinking about it I have a hard time seeing how it could work in another way. If the beans were not destroyed in the reverse order it would cause a lot of problems. For example, during the shutdown of an app a bean could try to use another bean that has already been destroyed. Unfortunately, I still haven’t found any confirmation of the behavior in the documentation.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement