Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define spring bean destroy method order

Tags:

java

spring

I have two beans BeanA and BeanB with destroy method defined by DisposableBean.

There is a requirement that the destroy method of BeanB must be invoked after the destroy method of BeanA.

How to implement that?

like image 213
梁雨生 Avatar asked Oct 20 '25 03:10

梁雨生


1 Answers

As you mentioned in comment beans are singletons, you can use depends_on. See Spring framework reference says as follows here

The depends-on attribute can specify both an initialization-time dependency and, in the case of singleton beans only, a corresponding destruction-time dependency. Dependent beans that define a depends-on relationship with a given bean are destroyed first, prior to the given bean itself being destroyed. Thus, depends-on can also control shutdown order.

If you prefer to use annotation based solution, you can use @DependsOn. Javadoc says as follows:

Dependent beans that define a depends-on relationship with a given bean are destroyed first, prior to the given bean itself being destroyed. Thus, a depends-on declaration can also control shutdown order.

like image 128
Steephen Avatar answered Oct 21 '25 16:10

Steephen