梁雨生
梁雨生

Reputation: 385

Define spring bean destroy method order

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?

Upvotes: 4

Views: 5069

Answers (1)

Steephen
Steephen

Reputation: 15824

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.

Upvotes: 4

Related Questions